Building AI Applications

Text Generation & Summarization

Build applications for content generation, summarization, translation, and text transformation using LLMs.

Text Generation & Summarization

Beyond chatbots, LLMs excel at generating, transforming, and condensing text. This topic covers building practical text processing applications.

Content Generation

Blog Post Generator

python
from openai import OpenAI

client = OpenAI()

def generate_blog_post(topic, audience, word_count=800):
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {
                "role": "system",
                "content": f"""You are a technical content writer.
                Write for: {audience}
                Style: Clear, practical, with code examples where relevant.
                Format: Use H2 headings, bullet points, and code blocks."""
            },
            {
                "role": "user",
                "content": f"Write a {word_count}-word blog post about: {topic}"
            }
        ],
        temperature=0.7,
        max_tokens=2000
    )
    return response.choices[0].message.content

Email Generator

python
def generate_email(context, tone="professional"):
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": f"Write {tone} emails. Be concise. "
                           f"Include subject line."
            },
            {
                "role": "user",
                "content": f"Write an email for this situation: {context}"
            }
        ],
        temperature=0.6,
        max_tokens=500
    )
    return response.choices[0].message.content

# Usage
email = generate_email(
    "Follow up with a client who hasn't responded to our proposal in 5 days",
    tone="friendly but professional"
)

Text Summarization

Simple Summary

python
def summarize(text, max_sentences=3):
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": f"Summarize the given text in exactly "
                           f"{max_sentences} sentences. Be concise and "
                           f"capture the key points."
            },
            {
                "role": "user",
                "content": text
            }
        ],
        temperature=0.3,  # Low temperature for accuracy
        max_tokens=300
    )
    return response.choices[0].message.content

Structured Summary

python
def structured_summary(text):
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {
                "role": "user",
                "content": f"""Analyze this text and provide a structured summary:

## Key Points
- [Main takeaways as bullet points]

## Important Details
- [Supporting facts and figures]

## Action Items
- [Any recommended actions or next steps]

Text to analyze:
{text}"""
            }
        ],
        temperature=0.3,
        max_tokens=500
    )
    return response.choices[0].message.content

Multi-Document Summary

python
def summarize_multiple_docs(documents):
    # Step 1: Summarize each document individually
    summaries = []
    for doc in documents:
        summary = summarize(doc, max_sentences=2)
        summaries.append(summary)

    # Step 2: Create a combined summary
    combined = "\n\n".join(
        f"Document {i+1}: {s}" for i, s in enumerate(summaries)
    )

    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {
                "role": "user",
                "content": f"""These are summaries of {len(documents)} documents.
                Create a unified summary that identifies common themes,
                contradictions, and key insights across all documents.

                {combined}"""
            }
        ],
        temperature=0.3
    )
    return response.choices[0].message.content

Text Transformation

Translation

python
def translate(text, target_language, preserve_formatting=True):
    instruction = f"Translate to {target_language}."
    if preserve_formatting:
        instruction += " Preserve all formatting, markdown, and code blocks."

    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {"role": "system", "content": instruction},
            {"role": "user", "content": text}
        ],
        temperature=0.3
    )
    return response.choices[0].message.content

Tone Adjustment

python
def adjust_tone(text, target_tone):
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": f"Rewrite the given text in a {target_tone} tone. "
                           f"Keep the same meaning and information."
            },
            {"role": "user", "content": text}
        ],
        temperature=0.6
    )
    return response.choices[0].message.content

# Usage
formal = adjust_tone("Hey! This product is super cool!", "formal business")
# → "We are pleased to present this exceptional product."

Text Simplification

python
def simplify(text, reading_level="8th grade"):
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "system",
                "content": f"Rewrite text at a {reading_level} reading level. "
                           f"Use simple words. Break long sentences into shorter ones."
            },
            {"role": "user", "content": text}
        ],
        temperature=0.4
    )
    return response.choices[0].message.content

Extraction

Named Entity Extraction

python
def extract_entities(text):
    response = client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {
                "role": "user",
                "content": f"""Extract named entities from this text as JSON:

{{
  "people": [],
  "organizations": [],
  "locations": [],
  "dates": [],
  "amounts": []
}}

Text: {text}"""
            }
        ],
        response_format={"type": "json_object"},
        temperature=0
    )
    import json
    return json.loads(response.choices[0].message.content)

Key Information Extraction

python
def extract_from_resume(resume_text):
    response = client.chat.completions.create(
        model="gpt-4o",
        messages=[
            {
                "role": "user",
                "content": f"""Extract the following from this resume as JSON:

{{
  "name": "",
  "email": "",
  "phone": "",
  "skills": [],
  "experience_years": 0,
  "education": [
    {{"degree": "", "institution": "", "year": ""}}
  ],
  "most_recent_role": ""
}}

Resume:
{resume_text}"""
            }
        ],
        response_format={"type": "json_object"},
        temperature=0
    )
    import json
    return json.loads(response.choices[0].message.content)

Batch Processing

For processing many documents efficiently:

python
import asyncio
from openai import AsyncOpenAI

async_client = AsyncOpenAI()

async def summarize_async(text):
    response = await async_client.chat.completions.create(
        model="gpt-4o-mini",
        messages=[
            {"role": "system", "content": "Summarize in 2 sentences."},
            {"role": "user", "content": text}
        ],
        temperature=0.3,
        max_tokens=200
    )
    return response.choices[0].message.content

async def batch_summarize(documents, batch_size=5):
    results = []
    for i in range(0, len(documents), batch_size):
        batch = documents[i:i + batch_size]
        summaries = await asyncio.gather(
            *[summarize_async(doc) for doc in batch]
        )
        results.extend(summaries)
    return results

# Usage
documents = ["doc1 text...", "doc2 text...", ...]
summaries = asyncio.run(batch_summarize(documents))

Quality Considerations

Temperature Guidelines

TaskTemperatureWhy
Summarization0.1–0.3Accuracy over creativity
Translation0.2–0.4Preserve meaning
Blog writing0.6–0.8Creative but coherent
Marketing copy0.7–0.9Maximum creativity
Data extraction0.0Exact parsing required

Handling Long Documents

When input exceeds the context window:

  1. Chunking: Split into overlapping chunks, process each, then combine
  2. Map-Reduce: Summarize each chunk, then summarize the summaries
  3. Use long-context models: Claude (200K) or Gemini (2M) for large documents

Key Takeaways

  1. Match temperature to task — lower for accuracy, higher for creativity
  2. Use JSON mode for structured extraction
  3. Batch with async for processing multiple documents
  4. Chunk long documents when they exceed context limits
  5. Validate outputs — LLMs can miss details or hallucinate

Next, we'll explore building code generation assistants.