Spaces:
Sleeping
Sleeping
Download app.py from Samir433/BlogWriterAgent: direct link, hf CLI and curl.
- Browser
- Download file 5.61 kB
-
https://huggingface.co/spaces/Samir433/BlogWriterAgent/resolve/main/app.py
- Command line
-
hf download hf://spaces/Samir433/BlogWriterAgent/app.py
-
curl -L -o app.py https://huggingface.co/spaces/Samir433/BlogWriterAgent/resolve/main/app.py
5.61 kB
| 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.") |