File size: 5,672 Bytes
f4ae53e
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
149
import os
import openai
import requests
import json
from openai import OpenAI
from dotenv import load_dotenv

# Load environment variables
load_dotenv()

# Initialize OpenAI client
client = OpenAI(api_key=os.getenv('OPENAI_API_KEY'))

class ArticleAgent:
    def __init__(self):
        self.model = os.getenv("OPENAI_VERSION")
        self.image_size = "1024x1024"
        
    def generate_article(self, title):
        """Generate a complete article from a title"""
        try:
            # Generate article outline
            outline = self._generate_outline(title)
            
            # Generate full article
            article = self._generate_full_article(title, outline)
            
            # Generate image
            image_url = self._generate_image(title)
            
            # Generate additional resources
            resources = self._generate_resources(title)
            
            return {
                "title": title,
                "outline": outline,
                "article": article,
                "image_url": image_url,
                "additional_resources": resources
            }
            
        except Exception as e:
            print(f"Error generating article: {str(e)}")
            return None
    
    def _generate_outline(self, title):
        """Generate an outline for the article"""
        prompt = f"""Create a detailed outline for an article titled: "{title}". 
        The outline should include an introduction, 3-5 main sections with 2-3 subsections each, 
        and a conclusion. Format the response in markdown."""
        
        response = client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "You are a professional content creator who creates well-structured article outlines."},
                {"role": "user", "content": prompt}
            ]
        )
        
        return response.choices[0].message.content
    
    def _generate_full_article(self, title, outline):
        """Generate the full article based on title and outline"""
        prompt = f"""Write a comprehensive, well-researched article with the following details:
        Title: {title}
        
        Outline:
        {outline}
        
        The article should be well-structured, engaging, and informative. Include relevant examples and data where appropriate.
        Format the response in markdown with proper headings, subheadings, and paragraphs."""
        
        response = client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "You are a professional writer who creates high-quality, engaging articles."},
                {"role": "user", "content": prompt}
            ]
        )
        
        return response.choices[0].message.content
    
    def _generate_image(self, title):
        """Generate an image for the article headline"""
        try:
            response = client.images.generate(
                model="dall-e-3",
                prompt=f"Create a professional, high-quality image that represents the following article title: {title}. The image should be suitable for a blog post header.",
                size=self.image_size,
                quality="standard",
                n=1,
            )
            return response.data[0].url
        except Exception as e:
            print(f"Error generating image: {str(e)}")
            return None
    
    def _generate_resources(self, title):
        """Generate additional resources related to the article topic"""
        prompt = f"""Provide 3-5 high-quality, authoritative resources (websites, books, research papers) 
        for readers who want to learn more about: {title}.
        
        Format the response as a markdown list with brief descriptions for each resource."""
        
        response = client.chat.completions.create(
            model=self.model,
            messages=[
                {"role": "system", "content": "You are a research assistant who provides valuable resources for further reading."},
                {"role": "user", "content": prompt}
            ]
        )
        
        return response.choices[0].message.content

# Example usage
if __name__ == "__main__":
    agent = ArticleAgent()
    
    # Example title - you can replace this with any title
    example_title = "The Future of Artificial Intelligence in Healthcare"
    
    print(f"Generating article for: {example_title}")
    result = agent.generate_article(example_title)
    
    if result:
        # Save the results to files
        os.makedirs("generated_articles", exist_ok=True)
        base_filename = f"generated_articles/{example_title.lower().replace(' ', '_')[:50]}"
        
        with open(f"{base_filename}_article.md", "w") as f:
            f.write(f"# {result['title']}\n\n")
            f.write("## Outline\n\n")
            f.write(result['outline'])
            f.write("\n\n## Article\n\n")
            f.write(result['article'])
            f.write("\n\n## Additional Resources\n\n")
            f.write(result['additional_resources'])
        
        # Save image URL
        with open(f"{base_filename}_image.txt", "w") as f:
            f.write(f"Image URL: {result['image_url']}")
        
        print(f"\nArticle generated successfully!")
        print(f"- Article saved to: {base_filename}_article.md")
        print(f"- Image URL saved to: {base_filename}_image.txt")
        print(f"\nImage URL: {result['image_url']}")
    else:
        print("Failed to generate article. Please check your API key and try again.")