File size: 2,529 Bytes
bb74076
 
 
 
 
 
 
 
 
 
 
 
 
 
d47a636
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
bb74076
d47a636
bb74076
d47a636
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
import gradio as gr
from phi.agent import Agent
from phi.model.groq import Groq
from phi.tools.duckduckgo import DuckDuckGo
from phi.tools.newspaper4k import Newspaper4k
import os
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Access the Groq API key
groq_api_key = os.getenv("GROQ_API_KEY")

# Initialize the agent
try:
    agent = Agent(
        model=Groq(id="llama-3.3-70b-versatile", api_key=groq_api_key),
        tools=[DuckDuckGo(), Newspaper4k()],
        description="You are a senior NYT researcher writing an article on a topic.",
        instructions=[
            "For a given topic, search for the top 5 links.",
            "Then read each URL and extract the article text, if a URL isn't available, ignore it.",
            "Analyse and prepare an NYT-worthy article based on the information.",
        ],
        markdown=True,
        show_tool_calls=True,
        add_datetime_to_instructions=True,
    )
except Exception as e:
    # Print error if the agent initialization fails
    raise RuntimeError(f"Error initializing the agent: {e}")

# Function to process input and generate an article
def generate_article(topic):
    if not topic.strip():
        return "Please enter a valid topic."

    try:
        response = agent.run(topic)  # Use `run` for robustness
        # Handle different response types
        if isinstance(response, str):
            return response  # Direct string output
        elif isinstance(response, list):
            return "\n".join(response)  # List of strings
        elif hasattr(response, 'content'):  # Response object with `content` attribute
            return response.content
        else:
            return f"Unexpected response type: {type(response)}. Raw output: {response}"
    except Exception as e:
        return f"Error generating the article: {e}"

# Gradio interface
with gr.Blocks() as app:
    gr.Markdown("# 📰 NYT-Style Article Generator")
    gr.Markdown(
        "Enter a topic below, and the app will generate an NYT-style article by searching, extracting, and summarizing information from the web."
    )

    with gr.Row():
        topic_input = gr.Textbox(
            label="Enter Topic", placeholder="e.g., Simulation Theory", lines=1
        )
        generate_button = gr.Button("Generate Article")

    output_text = gr.Markdown(label="Generated Article")

    generate_button.click(fn=generate_article, inputs=topic_input, outputs=output_text)

# Run the app
if __name__ == "__main__":
    app.launch()