Build Your Own AI Text Summarizer in Python with OpenAI API


With the amount of content we consume daily, summarization tools are becoming essential. Imagine pasting in any long article, report, or blog post and instantly getting a concise, clear summary.
In this tutorial, you’ll build a Python script that:
Accepts a text file or URL
Sends it to OpenAI’s API
Returns a short, readable summary
Step 1: Install Dependencies
bashCopyEditpip install openai requests beautifulsoup4
Step 2: Get Your API Key
Create an account at OpenAI
Copy your API key from the dashboard
Store it as an environment variable:
bashCopyEditexport OPENAI_API_KEY="your_api_key_here"
Step 3: Summarizer Code
pythonCopyEditimport os
import openai
import requests
from bs4 import BeautifulSoup
openai.api_key = os.getenv("OPENAI_API_KEY")
def fetch_text_from_url(url):
response = requests.get(url)
soup = BeautifulSoup(response.text, "html.parser")
return " ".join([p.get_text() for p in soup.find_all("p")])
def summarize_text(text, max_words=100):
prompt = f"Summarize the following text in under {max_words} words:\n\n{text}"
response = openai.ChatCompletion.create(
model="gpt-4o-mini",
messages=[{"role": "user", "content": prompt}],
temperature=0.5
)
return response.choices[0].message["content"].strip()
if __name__ == "__main__":
url = input("Enter article URL: ")
article_text = fetch_text_from_url(url)
summary = summarize_text(article_text, max_words=80)
print("\nSummary:\n", summary)
How It Works
The script uses
requests
andBeautifulSoup
to scrape text from the given URL.The extracted text is sent to OpenAI with a summarization prompt.
The API responds with a concise summary.
Example Run
bashCopyEditEnter article URL: https://example.com/ai-news
Summary:
AI adoption is accelerating across industries, driven by efficiency gains, automation, and new consumer applications. Ethical concerns and regulation remain key challenges.
Real-World Applications
Summarizing tech news articles
Creating digest versions of research papers
Automating newsletter content
Shortening meeting transcripts or long emails
Bonus: Turn It Into a CLI Tool
You can enhance this with argparse
to allow:
bashCopyEditpython summarize.py --url https://example.com/article --words 60
Conclusion
In just a few lines of Python, you can create a fully functional AI summarizer to help you process information faster. By combining this with scheduling tools, you could even set up automated daily summaries for your favorite sources.
Subscribe to my newsletter
Read articles from Ashraful Islam Leon directly inside your inbox. Subscribe to the newsletter, and don't miss out.
Written by

Ashraful Islam Leon
Ashraful Islam Leon
Passionate Software Developer | Crafting clean code and elegant solutions