How to summarize text with OpenAI API
Quick answer
Use the
OpenAI Python SDK to call client.chat.completions.create with a summarization prompt and a model like gpt-4o. Pass the text to summarize in the messages array and extract the summary from the response's choices[0].message.content.PREREQUISITES
Python 3.8+OpenAI API key (free tier works)pip install openai>=1.0
Setup
Install the official openai Python package and set your API key as an environment variable.
pip install openai>=1.0 output
Collecting openai Downloading openai-1.x.x-py3-none-any.whl (xx kB) Installing collected packages: openai Successfully installed openai-1.x.x
Step by step
This example shows how to summarize a long text using the gpt-4o model with the OpenAI Python SDK v1.
import os
from openai import OpenAI
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
text_to_summarize = (
"OpenAI provides powerful language models that can perform a variety of tasks, "
"including text summarization, translation, and question answering. "
"Using the chat completion endpoint, you can prompt the model to generate concise summaries."
)
messages = [
{"role": "user", "content": f"Please summarize the following text:\n\n{text_to_summarize}"}
]
response = client.chat.completions.create(
model="gpt-4o",
messages=messages
)
summary = response.choices[0].message.content
print("Summary:", summary) output
Summary: OpenAI's language models can perform various tasks such as summarization, translation, and question answering by using the chat completion endpoint to generate concise summaries.
Common variations
- Use
gpt-4o-minifor faster, cheaper summaries with slightly less detail. - Use async calls with
asynciofor concurrent summarization tasks. - Stream partial summary results by setting
stream=Truein the request.
import os
import asyncio
from openai import OpenAI
async def async_summarize(text: str):
client = OpenAI(api_key=os.environ["OPENAI_API_KEY"])
messages = [{"role": "user", "content": f"Summarize this text:\n\n{text}"}]
stream = await client.chat.completions.acreate(
model="gpt-4o-mini",
messages=messages,
stream=True
)
summary = ""
async for chunk in stream:
delta = chunk.choices[0].delta.content or ""
print(delta, end="", flush=True)
summary += delta
print()
return summary
if __name__ == "__main__":
text = "OpenAI's models can summarize text efficiently and accurately."
asyncio.run(async_summarize(text)) output
OpenAI's models can summarize text efficiently and accurately.
Troubleshooting
- If you get an authentication error, verify your
OPENAI_API_KEYenvironment variable is set correctly. - If the summary is too short or irrelevant, try refining the prompt or increasing
max_tokens. - For rate limit errors, implement exponential backoff retries.
Key Takeaways
- Use the OpenAI Python SDK v1 with
client.chat.completions.createfor summarization. - Pass the text in a user message prompt and extract the summary from the response content.
- Leverage streaming or async calls for efficient and scalable summarization workflows.