Spaces:
Sleeping
Sleeping
File size: 5,606 Bytes
a9935bd | 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 | import streamlit as st
from langchain_huggingface import ChatHuggingFace, HuggingFaceEndpoint
from langchain_google_genai import ChatGoogleGenerativeAI
from langchain.schema import HumanMessage
from langgraph.graph import StateGraph, START, END
from typing import TypedDict
from dotenv import load_dotenv
import os
# Load environment variables from a .env file
load_dotenv()
# --- Page Configuration ---
st.set_page_config(
page_title="AI Blog Writer",
page_icon="🤖",
layout="wide"
)
# --- API Key Management ---
# Make sure to create a .env file in the same directory with:
# GOOGLE_API_KEY="your_google_api_key"
# HUGGINGFACEHUB_API_TOKEN="your_huggingface_api_token"
google_api_key = os.getenv("GOOGLE_API_KEY")
huggingface_token = os.getenv("HUGGINGFACEHUB_API_TOKEN")
# --- LangGraph State Definition ---
class BlogState(TypedDict):
"""
Represents the state of our blog generation graph. It holds the data
that moves between the nodes of the graph.
"""
topic: str
blog_outline: str
final_blog: str
# --- Model Initialization ---
def initialize_models():
"""
Initializes and returns the language models.
Handles errors if API keys are missing.
"""
if not google_api_key:
st.error("Google API key is missing. Please set it in your .env file.")
return None, None
if not huggingface_token:
st.error("Hugging Face API token is missing. Please set it in your .env file.")
return None, None
try:
gemini = ChatGoogleGenerativeAI(
model="gemini-1.5-flash",
temperature=1.0,
max_retries=2,
google_api_key=google_api_key,
)
mistral_llm = HuggingFaceEndpoint(
repo_id="mistralai/Mistral-7B-Instruct-v0.2",
task="text-generation",
huggingfacehub_api_token=huggingface_token,
)
mistral = ChatHuggingFace(llm=mistral_llm)
return gemini, mistral
except Exception as e:
st.error(f"Failed to initialize models: {e}")
return None, None
gemini, mistral = initialize_models()
# --- LangGraph Node Functions ---
def outline_gen_node(state: BlogState) -> BlogState:
"""Node to generate the blog outline using the Mistral model."""
print("Executing outline generation node...")
with st.status("Generating blog outline...", expanded=True) as status:
response = mistral.invoke([
HumanMessage(content=f"Create a detailed blog outline on the topic: {state['topic']}. Be comprehensive and structure it logically for a compelling article.")
])
status.update(label="Outline generated!", state="complete")
state['blog_outline'] = response.content
return state
def blog_gen_node(state: BlogState) -> BlogState:
"""Node to generate the final blog post using the Gemini model."""
print("Executing blog generation node...")
blog_outline = state["blog_outline"]
with st.status("Writing the final blog post...", expanded=True) as status:
response = gemini.invoke([
HumanMessage(content=f"Write a detailed, engaging, and well-written blog post based on the following outline. Use markdown for formatting, including headings, bold text, and lists where appropriate. Make it ready for publishing.\n\n## Blog Outline\n{blog_outline}")
])
status.update(label="Blog post complete!", state="complete")
state["final_blog"] = response.content
return state
# --- Graph and Workflow Compilation ---
if gemini and mistral:
# Define the state graph
graph = StateGraph(BlogState)
# Add nodes to the graph
graph.add_node("outline_gen", outline_gen_node)
graph.add_node("blog_gen", blog_gen_node)
# Add edges to define the flow
graph.add_edge(START, "outline_gen")
graph.add_edge("outline_gen", "blog_gen")
graph.add_edge("blog_gen", END)
# Compile the graph into a runnable workflow
workflow = graph.compile()
else:
workflow = None
# --- Streamlit User Interface ---
st.title("🤖 AI Blog Writer")
st.markdown("Enter a topic and let two AI models collaborate to write a blog post. Mistral creates the outline, and Gemini writes the content.")
st.sidebar.header("How It Works")
st.sidebar.info(
"""
This app uses a **LangGraph** workflow to automate blog writing:
1. **You Enter a Topic**: Provide a subject for the blog post.
2. **Outline Generation**: A `Mistral-7B` model generates a detailed outline.
3. **Blog Generation**: Google's `Gemini` model writes the full blog post based on the outline.
4. **Final Output**: The final, formatted blog post is displayed.
"""
)
topic = st.text_input("Enter the blog topic here:", placeholder="e.g., The Impact of AI on Software Development")
if st.button("Generate Blog Post", disabled=(not workflow)):
if topic:
# Define the initial state for the graph
initial_state = BlogState(topic=topic, blog_outline="", final_blog="")
# Invoke the workflow
final_state = workflow.invoke(initial_state)
# Display the final blog
st.divider()
st.subheader("Your Generated Blog Post")
st.markdown(final_state['final_blog'])
else:
st.warning("Please enter a topic to generate a blog post.")
if not workflow:
st.error("Workflow could not be initialized. Please check your API keys and environment setup.") |