article-agent / article_agent.py
caveprod's picture
Upload 12 files
f4ae53e verified
Raw History Blame Contribute Delete
5.67 kB
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.")