In this tutorial, we’ll build a Streamlit Python App for an AI Blog Writer. This app will allow users to specify their blog preferences, generate AI-powered blog content, and refine it—all in a user-friendly interface. We’ll leverage the deepseek_text_response function to handle prompt-based AI responses.
Why Build an AI Blog Writer App?
Creating blog posts can be daunting when you're dealing with tight deadlines or writer's block. With an AI-powered tool like this, you can:
Generate well-structured, engaging blogs in minutes.
Customize tone, length, and audience for each post.
Focus on strategy while AI handles the writing.
This app will streamline your blog creation process and ensure that your content always hits the mark.
What You'll Build
Features of the AI Blog Writer App
User Preferences: Gather inputs such as blog topic, tone, audience, and length.
Custom Prompts: Automatically craft detailed AI prompts based on user preferences.
AI-Powered Writing: Use the deepseek_text_response function to generate blogs.
Preview and Export: Let users view and download their blog posts.
Prerequisites
Before we begin, ensure you have the following installed:
Python 3.8+
Streamlit: Install with pip install streamlit
Required Python Libraries:
requests
openai (if using OpenAI)
Any additional libraries for content formatting or export
How It Works
User Preferences: Users enter their blog requirements (topic, tone, audience, etc.).
AI Prompt: The app generates a detailed prompt using their inputs.
AI Response: The deepseek_text_response function sends the prompt to Alwrity’s AI and retrieves the content.
Blog Display: Users can preview, refine, and download the generated blog.
Detailed Steps to Build the App
Step 1: Setting Up the deepseek_text_response Function
The deepseek_text_response function is the backbone of this app. It processes the prompt and generates content using an AI model.
import requests
def deepseek_text_response(prompt, model="gpt-4", api_key="your_api_key"):
"""Fetch AI-generated text for a given prompt."""
headers = {
"Authorization": f"Bearer {api_key}",
"Content-Type": "application/json"
}
payload = {
"model": model,
"messages": [{"role": "user", "content": prompt}]
}
response = requests.post(
"https://api.openai.com/v1/chat/completions",
headers=headers,
json=payload
)
if response.status_code == 200:
return response.json()["choices"][0]["message"]["content"]
else:
raise Exception(f"Error: {response.status_code}, {response.text}")
Step 2: Building the Streamlit App
Import Libraries:
import streamlit as st
import json
Create the UI for Blog Preferences:
Here, users will specify their blog requirements.
def get_user_preferences():
st.title("AI Blog Writer")
st.write("Customize your blog preferences below:")
# Blog topic input
topic = st.text_input("Enter the topic of your blog:", placeholder="E.g., Benefits of Remote Work")
# Blog length options
length = st.selectbox("Preferred blog length:", ["Short (300-500 words)", "Medium (500-800 words)", "Long (800+ words)"])
# Audience demographic
audience = st.text_input("Describe your target audience:", placeholder="E.g., young professionals, students, tech enthusiasts")
# Blog tone
tone = st.selectbox("Select the tone of the blog:", ["Formal", "Conversational", "Inspirational", "Humorous"])
# Call to Action
cta = st.text_input("Add a call-to-action for the blog (optional):", placeholder="E.g., 'Subscribe now', 'Learn more'")
if st.button("Generate Blog"):
return {
"topic": topic,
"length": length,
"audience": audience,
"tone": tone,
"cta": cta
}
return None
Generate the AI Prompt:
Using user inputs, construct a detailed AI prompt.
def generate_prompt(preferences):
prompt = f"""
Write a {preferences['length'].lower()} blog post on the topic: "{preferences['topic']}".
The blog should be written for {preferences['audience']}.
Use a {preferences['tone'].lower()} tone throughout.
If applicable, include the following call-to-action: {preferences['cta']}.
Ensure the blog is engaging, well-structured, and informative.
"""
return prompt
Integrate deepseek_text_response:
Call the function to fetch the blog content.
def fetch_blog_content(prompt, api_key):
try:
return deepseek_text_response(prompt, api_key=api_key)
except Exception as e:
return f"Error generating content: {e}"
Display the Generated Blog:
Use Streamlit to display the generated blog content.
def display_blog(content):
st.subheader("Generated Blog")
st.markdown(content, unsafe_allow_html=True)
st.download_button("Download Blog", content, file_name="blog.txt")
Step 3: Combining Everything
Here’s the complete code to run your app:
import streamlit as st
from deepseek_function import deepseek_text_response # Assuming it's in a separate file
def get_user_preferences():
st.title("AI Blog Writer")
st.write("Customize your blog preferences below:")
topic = st.text_input("Enter the topic of your blog:", placeholder="E.g., Benefits of Remote Work")
length = st.selectbox("Preferred blog length:", ["Short (300-500 words)", "Medium (500-800 words)", "Long (800+ words)"])
audience = st.text_input("Describe your target audience:", placeholder="E.g., young professionals, students, tech enthusiasts")
tone = st.selectbox("Select the tone of the blog:", ["Formal", "Conversational", "Inspirational", "Humorous"])
cta = st.text_input("Add a call-to-action for the blog (optional):", placeholder="E.g., 'Subscribe now', 'Learn more'")
if st.button("Generate Blog"):
return {
"topic": topic,
"length": length,
"audience": audience,
"tone": tone,
"cta": cta
}
return None
def generate_prompt(preferences):
prompt = f"""
Write a {preferences['length'].lower()} blog post on the topic: "{preferences['topic']}".
The blog should be written for {preferences['audience']}.
Use a {preferences['tone'].lower()} tone throughout.
If applicable, include the following call-to-action: {preferences['cta']}.
Ensure the blog is engaging, well-structured, and informative.
"""
return prompt
def main():
st.sidebar.title("AI Blog Writer Settings")
st.sidebar.write("Adjust preferences for your blog.")
preferences = get_user_preferences()
if preferences:
prompt = generate_prompt(preferences)
st.write("AI Prompt:")
st.code(prompt)
api_key = st.text_input("Enter your API key:", type="password")
if api_key:
blog_content = fetch_blog_content(prompt, api_key)
display_blog(blog_content)
if __name__ == "__main__":
main()
Conclusion
This blog app empowers users to create tailored, AI-generated blog posts with minimal effort. By leveraging deepseek_text_response and a user-friendly Streamlit interface, you can easily customize and generate blogs on any topic, enhancing productivity and creativity. 🎉
Comments