AI Patterns: Practical Tutorial for Building AI Applications with Python

Learn how to build practical AI applications using AI application patterns, Large Language Models (LLMs), and Python. This hands-on tutorial introduces the fundamental patterns used in modern AI engineering, explaining how to apply them to real-world software development problems.

AI Pattern Python Practical Tutorial

You will explore essential AI patterns, including Classification, Information Extraction, Text Summarization, Content Generation, Embeddings, Semantic Similarity, Retrieval-Augmented Generation (RAG), and Tool Calling. Each concept focuses on understanding the underlying architecture, implementing the workflow in Python, validating model outputs, and testing application behaviour.

Through practical examples and hands-on exercises, you will learn how to integrate LLMs into Python applications, process unstructured data, retrieve relevant information from documents, generate structured responses, and connect AI models with application-level tools.

The tutorial also explains when to use an AI model and when traditional programming techniques such as Python functions, regular expressions, SQL queries, and rule-based logic are more suitable.

Learn the concepts, implement the patterns, test the results, and build your own Technical AI Application Patterns Lab using Python.

Table of Contents

  1. Part 1 - Curriculum Alignment, Introduction, Prerequisites, and LLM Application Architecture
  2. Part 2 - Classification and Information Extraction
  3. Part 3 - Summarization and Generation

Part 1 - Curriculum Alignment, Introduction, Prerequisites, and LLM Application Architecture

Learn the foundations of AI application patterns and Large Language Model (LLM) application architecture in this practical introduction to Applied AI Engineering. This part explains how modern AI-powered applications are structured, how application patterns help solve recurring engineering problems, and how to integrate LLMs into Python applications.

Learning objectives

After completing all parts, you will be able to:

  • Identify which AI application pattern fits a given technical problem.
  • Explain the common architecture of an LLM-powered application.
  • Implement classification, extraction, summarization, and generation workflows.
  • Create and validate structured JSON outputs with Pydantic.
  • Use embeddings to compare semantic meaning.
  • Build a small retrieval-augmented generation demonstration.
  • Implement bounded tool calling with application-side execution.
  • Decide when deterministic code is better than an LLM.
  • Measure latency and token usage where available.
  • Estimate cost only when reliable usage and pricing data exist.
  • Handle timeouts, provider errors, invalid responses, and malformed model output.
  • Build a modular CLI application that combines these patterns.

Prerequisites

You should already understand:

  • Basic Python: functions, modules, type hints, exception handling, virtual environments.
  • Basic JSON and HTTP concepts.
  • Basic command-line usage in Windows PowerShell.
  • What an LLM, token, prompt, and context window are.
  • The difference between hosted and local inference.

You do not need prior experience with machine learning, model training, vector databases, or AI agents.

Install dependencies

Open PowerShell in your project folder:

PowerShell

python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
pip install httpx pydantic python-dotenv pytest

Optional hosted SDK-install only if you intend to use that provider:

PowerShell

pip install openai

Verify Ollama

PowerShell

ollama --version
ollama list

Expected output shape:

PowerShell

ollama version is 0.x.x
NAME              ID              SIZE      MODIFIED
granite4.2:3b     example-id      2.0 GB    2 days ago

Verify that the local service is reachable:

PowerShell

Invoke-RestMethod -Uri http://localhost:11434/api/version

If this fails, start Ollama and run the command again. Do not expose port 11434 to the public internet.

Module 1 - Understanding AI application patterns

What an application pattern is

An AI application pattern is a repeatable architectural approach for solving a category of problem with an AI model. Instead of treating every AI feature as a unique chatbot, an engineer identifies the underlying pattern:

  • “I need to assign a category” → classification.
  • “I need fields from free text” → extraction.
  • “I need a shorter version” → summarization.
  • “I need new content” → generation.
  • “I need meaning-based matching” → embeddings.
  • “I need answers grounded in documents” → RAG.
  • “I need an approved system action” → tool calling.

Patterns make systems easier to design, test, reuse, and operate.

Why patterns matter

Without patterns, AI features often become inconsistent prompts embedded in application code. With patterns, you can separate:

  • The user problem.
  • The application workflow.
  • The model request.
  • The output contract.
  • The validation rules.
  • The failure behavior.

This separation is essential for building reliable AI products.

Real-world examples

Problem Pattern Example
Route an incoming ticket Classification VPN fails → Network
Create a ticket record from an email Extraction Extract service, error code, affected user
Give an on-call engineer a quick incident overview Summarization Convert a long log into five findings
Draft troubleshooting guidance Generation Produce safe, reviewed remediation steps
Find similar past incidents Embeddings / semantic search Match “cannot reach database” to prior incidents
Answer questions from internal runbooks RAG Retrieve relevant runbook sections, then answer
Check current service status Tool calling LLM requests get_service_status, application executes it

Pattern comparison

Pattern Input Output Primary value Main risk
Classification Unstructured text One or more labels Consistent routing Ambiguous or invalid labels
Extraction Unstructured text Structured fields Automation and integration Missing or wrong fields
Summarization Long text Shorter text Faster human understanding Omission or hallucination
Generation Instruction and context New text Product functionality Unsafe or incorrect content
Embeddings Text Vector Semantic matching Poor similarity calibration
RAG Question plus documents Grounded answer Current/private knowledge Bad retrieval or unsupported claims
Tool calling User request Tool request and final answer Controlled system actions Unsafe or unintended execution

Relationship to the roadmap

These patterns are the application-layer foundation for later specialization:

Phase 1 concept Future specialization
Classification AI applications and intelligent automation
Extraction Structured AI data processing
Summarization Context processing and AI productivity
Generation AI-powered product functionality
Embeddings RAG and semantic retrieval
RAG fundamentals Advanced RAG Engineering
Tool calling Agentic AI and MCP
Deterministic logic Backend and harness reliability
Latency and token tracking Evaluation and observability

Module 2 - Common architecture of an LLM application

Core execution flow

Common architecture of an LLM application

This diagram represents the minimum reliable lifecycle for an LLM-backed feature:

  1. User input enters the application.
  2. Input validation rejects malformed, unsafe, or oversized input before spending tokens.
  3. Prompt construction combines instructions, constraints, and approved context.
  4. Model request sends the prompt to a hosted API or local runtime.
  5. Model response returns generated text or structured data.
  6. Output validation enforces the expected schema and business rules.
  7. Application result is returned to the user or passed to another system.
  8. Error handling catches validation, network, timeout, rate-limit, and provider failures.
  9. Logging and metrics record latency, token usage, errors, and outcomes without exposing secrets.

Responsibility boundaries

Component Responsible for Should not do
User interface Collecting input, displaying results Trusting model output blindly
Application logic Workflow, validation, business rules Embedding provider details everywhere
Prompt builder Creating clear, constrained instructions Including secrets or unvalidated data
Provider adapter Provider-specific API calls Making business decisions
Model Generating a response from the prompt Executing tools or accessing systems directly
Output validator Enforcing schema and rules Silently accepting malformed output
Observability layer Recording metrics and errors Logging API keys or sensitive user data

Deterministic versus model-dependent code

A well-designed AI application separates:

Deterministic code:
- Input validation
- Business rules
- Database access
- Mathematical calculations
- File and API access
- Output formatting

Model-dependent code:
- Natural-language classification
- Ambiguous extraction
- Summarization
- Explanation generation
- Semantic matching

The model should be treated as an unreliable, probabilistic component. Deterministic code should surround it with validation, limits, retries where safe, and fallbacks.

Minimal runnable architecture skeleton

Create app_pipeline.py:

Python

                    """Minimal LLM application pipeline skeleton.

                    This example uses local Ollama and demonstrates the separation between
                    application validation, prompt construction, provider access, and output
                    validation.
                    """

                    import os
                    import time
                    from typing import Any

                    import httpx
                    from pydantic import BaseModel, Field
                    from dotenv import load_dotenv

                    load_dotenv()


                    class PipelineError(Exception):
                        """Raised when the application pipeline cannot produce a valid result."""


                    class SummaryResult(BaseModel):
                        summary: str = Field(min_length=1, max_length=2_000)


                    def validate_input(text: str) -> str:
                        cleaned = text.strip()
                        if not cleaned:
                            raise PipelineError("Input text cannot be empty.")
                        if len(cleaned) > 10_000:
                            raise PipelineError("Input text exceeds the 10,000-character limit.")
                        return cleaned


                    def build_prompt(text: str) -> str:
                        return (
                            "Summarize the following technical text in exactly two sentences. "
                            "Do not add information that is not present in the text.\n\n"
                            f"Text:\n{text}"
                        )


                    def call_ollama(prompt: str) -> dict[str, Any]:
                        base_url = os.getenv("OLLAMA_BASE_URL", "http://localhost:11434").rstrip("/")
                        model = os.getenv("OLLAMA_MODEL", "granite4.2:3b")

                        started = time.perf_counter()

                        try:
                            response = httpx.post(
                                f"{base_url}/api/generate",
                                json={
                                    "model": model,
                                    "prompt": prompt,
                                    "stream": False,
                                    "options": {"temperature": 0.2},
                                },
                                timeout=120.0,
                            )
                            response.raise_for_status()
                        except httpx.TimeoutException as exc:
                            raise PipelineError("Model request timed out.") from exc
                        except httpx.ConnectError as exc:
                            raise PipelineError("Cannot connect to local Ollama service.") from exc
                        except httpx.HTTPStatusError as exc:
                            raise PipelineError(
                                f"Ollama returned HTTP {exc.response.status_code}."
                            ) from exc

                        latency_ms = (time.perf_counter() - started) * 1000
                        payload = response.json()

                        return {
                            "text": payload.get("response", "").strip(),
                            "latency_ms": latency_ms,
                            "input_tokens": payload.get("prompt_eval_count"),
                            "output_tokens": payload.get("eval_count"),
                        }


                    def validate_output(raw_text: str) -> SummaryResult:
                        try:
                            return SummaryResult(summary=raw_text)
                        except Exception as exc:
                            raise PipelineError("Model returned an invalid summary.") from exc


                    def summarize(text: str) -> dict[str, Any]:
                        validated_input = validate_input(text)
                        prompt = build_prompt(validated_input)
                        response = call_ollama(prompt)
                        result = validate_output(response["text"])

                        return {
                            "summary": result.summary,
                            "latency_ms": round(response["latency_ms"], 2),
                            "input_tokens": response["input_tokens"],
                            "output_tokens": response["output_tokens"],
                        }


                    def main() -> None:
                        text = (
                            "The application deployment failed because the PostgreSQL migration "
                            "timed out. The service could not connect to the database, and the "
                            "reverse proxy returned a 502 error."
                        )

                        try:
                            result = summarize(text)
                        except PipelineError as exc:
                            print(f"Pipeline error: {exc}")
                            raise SystemExit(1)

                        print(result["summary"])
                        print(f"Latency: {result['latency_ms']} ms")
                        print(f"Input tokens: {result['input_tokens']}")
                        print(f"Output tokens: {result['output_tokens']}")


                    if __name__ == "__main__":
                        main()
                                

Run the skeleton

PowerShell

python app_pipeline.py
                                

Expected output shape:

The deployment failed because the PostgreSQL migration timed out, preventing
the application from connecting to the database and causing a 502 error.
Latency: 4218.35 ms
Input tokens: 67
Output tokens: 38

Your latency and token counts will differ. Token availability also depends on the Ollama version, model, and API response fields.

Failure boundaries

Failure Where it should be handled Example response
Empty input Input validation Reject before model call
Oversized input Input validation or context budget check Reject or chunk/retrieve
Ollama unavailable Provider adapter Clear connection error
Timeout Provider adapter Fail fast or retry only safe operations
HTTP 429 Provider adapter Back off and retry with a cap
Invalid JSON Output validation Retry, repair, or return a controlled error
Hallucinated content Application review / evaluation Do not automatically trust factual claims

Observability fundamentals

At Phase 1, record:

  • Timestamp.
  • Pattern name.
  • Provider and model identifier.
  • Latency.
  • Input and output token counts when available.
  • Validation outcome.
  • Error category.
  • Prompt and output version.

Do not log:

  • API keys.
  • Full sensitive user content by default.
  • Secrets from environment variables.
  • Unredacted personal or confidential data.

Proposed integrated project architecture

technical-ai-patterns-lab/
├── .env.example
├── .gitignore
├── requirements.txt
├── README.md
├── main.py
├── sample_data/
│   ├── incident_log.txt
│   ├── support_ticket.txt
│   └── knowledge/
│       ├── nginx.md
│       └── postgres.md
├── app/
│   ├── __init__.py
│   ├── config.py
│   ├── cli.py
│   ├── providers/
│   │   ├── __init__.py
│   │   ├── base.py
│   │   ├── hosted.py
│   │   └── ollama.py
│   ├── patterns/
│   │   ├── __init__.py
│   │   ├── classification.py
│   │   ├── extraction.py
│   │   ├── summarization.py
│   │   ├── generation.py
│   │   ├── similarity.py
│   │   ├── rag.py
│   │   └── tool_calling.py
│   ├── deterministic/
│   │   ├── __init__.py
│   │   ├── extractors.py
│   │   ├── search.py
│   │   └── validators.py
│   ├── schemas/
│   │   ├── __init__.py
│   │   ├── classification.py
│   │   └── extraction.py
│   └── utilities/
│       ├── __init__.py
│       ├── latency.py
│       ├── token_usage.py
│       ├── cost.py
│       └── logging.py
└── tests/
    ├── __init__.py
    ├── test_classification.py
    ├── test_extraction.py
    ├── test_cost.py
    └── test_deterministic.py

Module responsibilities

Module Responsibility
main.py CLI entry point
config.py Environment and model configuration
providers/base.py Common provider interface
providers/ollama.py Local Ollama integration
providers/hosted.py Optional hosted-provider integration
patterns/classification.py Ticket and error classification
patterns/extraction.py Structured field extraction
patterns/summarization.py Technical summarization
patterns/generation.py Explanation and report generation
patterns/similarity.py Embeddings and cosine similarity
patterns/rag.py Basic retrieval and grounded answering
patterns/tool_calling.py Safe, bounded tool execution
deterministic/ Regex, keyword search, validation, rules
utilities/ Latency, token usage, cost, logging
schemas/ Pydantic output contracts
tests/ Unit and integration tests

This structure is intentionally simple. Avoid adding a web framework, vector database, agent framework, or orchestration system until a later phase requires one.

Complete learning sequence

Part Modules Primary deliverable
Part 1 Curriculum alignment, introduction, prerequisites, common architecture Runnable LLM application pipeline skeleton
Part 2 Classification and information extraction Validated classifier and extractor
Part 3 Summarization and generation Technical summarizer and safe generator
Part 4 Embeddings and semantic similarity Semantic comparison and basic search
Part 5 RAG fundamentals Small end-to-end RAG demonstration
Part 6 Tool-calling fundamentals Bounded tool-calling workflow
Part 7 Deterministic engineering vs. LLM Regex versus LLM extraction experiment
Part 8 Integrated project Technical AI Application Patterns Lab
Part 9 Testing, evaluation, mastery Test suite, assessment, and scorecard

Each later part will follow this sequence:

  1. Problem definition
  2. Concept explanation
  3. Technical terminology
  4. Engineering value
  5. Architecture
  6. Execution flow
  7. Prerequisites
  8. Environment setup
  9. Complete implementation
  10. Code walkthrough
  11. PowerShell execution
  12. Expected output
  13. Testing
  14. Failure analysis
  15. Performance and cost implications
  16. Engineering decisions
  17. Hands-on exercise
  18. Review checklist
  19. Hybrid specialization connection

Phase 1 versus later specialization

Topic Phase 1 treatment Later-phase treatment
Classification Basic LLM classification with validation Conventional ML, evaluation pipelines, production routing
Extraction JSON extraction with Pydantic Complex document pipelines, schema evolution
Summarization Short technical summaries Long-document workflows, evaluation, compression strategies
Generation Controlled technical generation Product features, templates, guardrails
Embeddings Local embeddings and cosine similarity Vector databases, hybrid search, indexing
RAG Minimal retrieve-and-answer demo Advanced RAG engineering
Tool calling Approved deterministic tools Agents, MCP, planning, multi-step workflows
Observability Latency, tokens, errors Tracing, dashboards, evaluation platforms
Security Input validation and localhost isolation Threat modeling, secrets, policy enforcement

Part 1 completion checklist

  • You can explain what an AI application pattern is.
  • You can name the seven Phase 1 patterns.
  • You can describe the common LLM application lifecycle.
  • You can distinguish application, model, provider, and validator responsibilities.
  • You can explain why deterministic code should surround model calls.
  • You installed the core Python dependencies.
  • You verified that Ollama is running.
  • You ran app_pipeline.py successfully.
  • You understand why API keys, sensitive content, and secrets must not be logged.
  • You understand which advanced topics are deferred to later phases.

Hands-on exercise

Objective: Modify app_pipeline.py so it rejects input containing the literal string IGNORE PREVIOUS INSTRUCTIONS.

Requirements:

  • Raise PipelineError before calling Ollama.
  • Return a clear error message.
  • Do not send the rejected input to the model.
  • Add at least one test using pytest.

Acceptance criteria:

  • Normal technical text is summarized.
  • Prompt-injection text is rejected before the provider call.
  • No API key or secret appears in output or logs.

Common mistakes:

  • Checking for injection only after calling the model.
  • Logging the full rejected input.
  • Treating prompt-injection detection as a complete security solution; it is only a basic Phase 1 control.

Review guidance: Your validation function should run before build_prompt() and call_ollama().

How this part contributes to becoming a Hybrid Applied AI Systems Engineer

This part develops the core competency of system boundary design. You learn to treat the LLM as one component inside a larger application, rather than as the application itself.

Later phases depend on this foundation:

  • Prompt and context engineering will build on prompt construction and validation.
  • AI application engineering will reuse provider abstraction and error handling.
  • RAG engineering will extend embeddings, retrieval, and context injection.
  • Agentic AI and MCP will extend bounded tool calling.
  • Evaluation and observability will extend latency, token, cost, and failure tracking.
  • Production reliability engineering will extend validation, fallbacks, logging, and security controls.

After completing this part, you should be able to decide independently where validation belongs, what the model should never be allowed to do directly, and which operational metrics must be captured.


Part 2 - Classification and Information Extraction

Module 3 - Classification

Problem definition

Technical teams receive large volumes of unstructured text: support tickets, incident reports, error messages, user questions, and maintenance requests. A common first step is to route each item to the correct team or workflow.

Example:

VPN connection fails after the latest client update.

A support system may need to route this to the Network team, while:

Laptop does not boot after Windows update.

should go to Hardware or Software, depending on your internal taxonomy.

Concept explanation

Classification assigns one or more predefined categories to an input. Unlike generation, classification constrains the model to a small, known output space.

Examples:

  • Network, Hardware, Software, Security
  • P1, P2, P3
  • beginner, intermediate, advanced
  • billing, authentication, performance

Technical terminology

Term Meaning
Class / label One allowed output category
Multi-class classification Choose exactly one label from many
Multi-label classification Choose zero or more applicable labels
Zero-shot classification Classify using instructions only, with no examples
Few-shot classification Include a small number of examples in the prompt
Structured output Model output constrained to a machine-readable format
Schema validation Checking that output matches a defined structure
Confidence A model-reported or derived measure of certainty

An LLM does not inherently “know” your business taxonomy. It must be told the allowed labels, output format, and decision rules.

Why it matters

Classification is often the first AI-powered step in a workflow. A reliable classifier can reduce manual triage, route incidents faster, and make downstream automation possible. But an incorrect classification can send a security incident to the wrong team or cause an automated workflow to take the wrong action.

Architecture

Classification architecture

The application—not the model—defines the allowed labels and rejects anything else.

Execution flow

  1. Validate that ticket text is present and within size limits.
  2. Build a prompt containing the allowed labels and JSON format.
  3. Send the prompt to Ollama or a hosted provider.
  4. Parse the returned text as JSON.
  5. Validate the label with Pydantic.
  6. Return the validated classification and operational metadata.
  7. If parsing or validation fails, return a controlled error or retry with a stricter instruction.

Prerequisites

Complete Part 1. You need:

  • Python virtual environment active.
  • httpx, pydantic, python-dotenv, and pytest installed.
  • Ollama running.
  • granite4.2:3b available locally.

Verify:

PowerShell

                                ollama list
                    Invoke-RestMethod -Uri http://localhost:11434/api/version
                                

Implementation

Create the project structure:

PowerShell

mkdir technical-ai-patterns-lab
cd technical-ai-patterns-lab
python -m venv .venv
.\.venv\Scripts\Activate.ps1
pip install httpx pydantic python-dotenv pytest
                                

Create .env:

Env

                                OLLAMA_BASE_URL=http://localhost:11434
                    OLLAMA_MODEL=granite4.2:3b
                                

Create .gitignore:

Gitignore

                                .venv/
                    __pycache__/
                    .env
                    .pytest_cache/
                                

Provider abstraction

Create app/providers/base.py:

Python

                                    """Common interface for model providers."""

                    from abc import ABC, abstractmethod
                    from dataclasses import dataclass
                    from typing import Any


                    @dataclass(frozen=True)
                    class ModelResponse:
                        text: str
                        latency_ms: float
                        input_tokens: int | None
                        output_tokens: int | None
                        error: str | None = None


                    class BaseModelProvider(ABC):
                        @abstractmethod
                        def generate(self, prompt: str, temperature: float = 0.0) -> ModelResponse:
                            """Send a prompt and return a normalized model response."""
                                    

Create app/providers/ollama.py:

Python

                                    """Ollama provider implementation."""

                    import os
                    import time
                    from typing import Any

                    import httpx

                    from app.providers.base import BaseModelProvider, ModelResponse


                    class OllamaProvider(BaseModelProvider):
                        def __init__(
                            self,
                            base_url: str | None = None,
                            model: str | None = None,
                            timeout_seconds: float = 120.0,
                        ) -> None:
                            self.base_url = (
                                base_url
                                or os.getenv("OLLAMA_BASE_URL", "http://localhost:11434")
                            ).rstrip("/")
                            self.model = model or os.getenv("OLLAMA_MODEL", "granite4.2:3b")
                            self.timeout_seconds = timeout_seconds

                        def generate(self, prompt: str, temperature: float = 0.0) -> ModelResponse:
                            started = time.perf_counter()

                            try:
                                response = httpx.post(
                                    f"{self.base_url}/api/generate",
                                    json={
                                        "model": self.model,
                                        "prompt": prompt,
                                        "stream": False,
                                        "options": {"temperature": temperature},
                                    },
                                    timeout=self.timeout_seconds,
                                )
                                response.raise_for_status()
                            except httpx.TimeoutException:
                                return ModelResponse("", 0.0, None, None, "timeout")
                            except httpx.ConnectError:
                                return ModelResponse("", 0.0, None, None, "connection_error")
                            except httpx.HTTPStatusError as exc:
                                status = exc.response.status_code
                                error = "rate_limited" if status == 429 else f"http_{status}"
                                return ModelResponse("", 0.0, None, None, error)

                            latency_ms = (time.perf_counter() - started) * 1000
                            payload: dict[str, Any] = response.json()

                            return ModelResponse(
                                text=payload.get("response", "").strip(),
                                latency_ms=latency_ms,
                                input_tokens=payload.get("prompt_eval_count"),
                                output_tokens=payload.get("eval_count"),
                            )
                                    

Create app/providers/__init__.py:

Python

                                    """Model provider package."""

                    from app.providers.base import BaseModelProvider, ModelResponse
                    from app.providers.ollama import OllamaProvider

                    __all__ = ["BaseModelProvider", "ModelResponse", "OllamaProvider"]
                                    

Classification schema

Create app/schemas/classification.py:

Python

                                    """Pydantic schemas for classification outputs."""

                    from pydantic import BaseModel, Field

                    ALLOWED_TICKET_LABELS = {"Network", "Hardware", "Software", "Security"}
                    ALLOWED_ERROR_CATEGORIES = {
                        "Configuration",
                        "Connectivity",
                        "Resource",
                        "Permission",
                        "Unknown",
                    }


                    class TicketClassification(BaseModel):
                        label: str = Field(pattern="^(Network|Hardware|Software|Security)$")
                        reasoning: str = Field(default="", max_length=500)


                    class ErrorClassification(BaseModel):
                        category: str = Field(
                            pattern="^(Configuration|Connectivity|Resource|Permission|Unknown)$"
                        )
                        reasoning: str = Field(default="", max_length=500)
                                    

Create app/schemas/__init__.py:

Python

                                    """Pydantic schema package."""

                    from app.schemas.classification import (
                        ALLOWED_ERROR_CATEGORIES,
                        ALLOWED_TICKET_LABELS,
                        ErrorClassification,
                        TicketClassification,
                    )

                    __all__ = [
                        "ALLOWED_ERROR_CATEGORIES",
                        "ALLOWED_TICKET_LABELS",
                        "ErrorClassification",
                        "TicketClassification",
                    ]
                                    

Classification pattern

Create app/patterns/classification.py:

Python

                                    """LLM-based classification pattern with strict output validation."""

                    import json

                    from pydantic import ValidationError

                    from app.providers.base import BaseModelProvider, ModelResponse
                    from app.schemas.classification import ErrorClassification, TicketClassification


                    class ClassificationError(Exception):
                        """Raised when classification cannot produce a valid result."""


                    def _build_ticket_prompt(text: str) -> str:
                        return (
                            "Classify the technical support ticket into exactly one category:\n"
                            "Network, Hardware, Software, Security.\n\n"
                            "Rules:\n"
                            "- Return only valid JSON.\n"
                            '- Use this exact JSON shape: {"label": "<label>", "reasoning": "<short reason>"}\n'
                            "- Do not include Markdown, explanations outside JSON, or extra fields.\n\n"
                            f"Ticket:\n{text}"
                        )


                    def _build_error_prompt(text: str) -> str:
                        return (
                            "Classify the Linux or infrastructure error into exactly one category:\n"
                            "Configuration, Connectivity, Resource, Permission, Unknown.\n\n"
                            "Rules:\n"
                            "- Return only valid JSON.\n"
                            '- Use this exact JSON shape: {"category": "<category>", "reasoning": "<short reason>"}\n'
                            "- Do not include Markdown or extra fields.\n\n"
                            f"Error:\n{text}"
                        )


                    def _parse_model_response(
                        response: ModelResponse,
                        schema_type: type[TicketClassification] | type[ErrorClassification],
                    ) -> TicketClassification | ErrorClassification:
                        if response.error:
                            raise ClassificationError(f"Model request failed: {response.error}")

                        if not response.text:
                            raise ClassificationError("Model returned an empty response.")

                        try:
                            payload = json.loads(response.text)
                        except json.JSONDecodeError as exc:
                            raise ClassificationError(
                                f"Model returned invalid JSON: {response.text!r}"
                            ) from exc

                        try:
                            return schema_type.model_validate(payload)
                        except ValidationError as exc:
                            raise ClassificationError(
                                f"Model output failed schema validation: {exc}"
                            ) from exc


                    def classify_ticket(
                        provider: BaseModelProvider,
                        text: str,
                    ) -> tuple[TicketClassification, ModelResponse]:
                        """Classify a technical support ticket into one allowed label."""

                        cleaned = text.strip()
                        if not cleaned:
                            raise ClassificationError("Ticket text cannot be empty.")
                        if len(cleaned) > 5_000:
                            raise ClassificationError("Ticket text exceeds the 5,000-character limit.")

                        prompt = _build_ticket_prompt(cleaned)
                        response = provider.generate(prompt, temperature=0.0)
                        result = _parse_model_response(response, TicketClassification)

                        if not isinstance(result, TicketClassification):
                            raise ClassificationError("Unexpected classification result type.")

                        return result, response


                    def classify_error(
                        provider: BaseModelProvider,
                        text: str,
                    ) -> tuple[ErrorClassification, ModelResponse]:
                        """Classify a Linux or infrastructure error into one allowed category."""

                        cleaned = text.strip()
                        if not cleaned:
                            raise ClassificationError("Error text cannot be empty.")
                        if len(cleaned) > 5_000:
                            raise ClassificationError("Error text exceeds the 5,000-character limit.")

                        prompt = _build_error_prompt(cleaned)
                        response = provider.generate(prompt, temperature=0.0)
                        result = _parse_model_response(response, ErrorClassification)

                        if not isinstance(result, ErrorClassification):
                            raise ClassificationError("Unexpected error classification result type.")

                        return result, response
                                    

Create app/patterns/__init__.py:

Python

                                    """AI application pattern implementations."""
                                    

Create app/__init__.py:

Python

                                    """Technical AI Application Patterns Lab."""
                                    

CLI command

Create classify_cli.py:

Python

                                    """Command-line interface for ticket and error classification."""

                    import argparse
                    import json
                    import sys

                    from app.patterns.classification import (
                        ClassificationError,
                        classify_error,
                        classify_ticket,
                    )
                    from app.providers.ollama import OllamaProvider


                    def main() -> int:
                        parser = argparse.ArgumentParser(prog="classify")
                        parser.add_argument(
                            "kind",
                            choices=["ticket", "error"],
                            help="Type of text to classify.",
                        )
                        parser.add_argument("text", help="Text to classify.")
                        args = parser.parse_args()

                        provider = OllamaProvider()

                        try:
                            if args.kind == "ticket":
                                result, response = classify_ticket(provider, args.text)
                                output = {
                                    "label": result.label,
                                    "reasoning": result.reasoning,
                                    "latency_ms": round(response.latency_ms, 2),
                                    "input_tokens": response.input_tokens,
                                    "output_tokens": response.output_tokens,
                                }
                            else:
                                result, response = classify_error(provider, args.text)
                                output = {
                                    "category": result.category,
                                    "reasoning": result.reasoning,
                                    "latency_ms": round(response.latency_ms, 2),
                                    "input_tokens": response.input_tokens,
                                    "output_tokens": response.output_tokens,
                                }

                            print(json.dumps(output, indent=2))
                            return 0

                        except ClassificationError as exc:
                            print(f"Classification failed: {exc}", file=sys.stderr)
                            return 1


                    if __name__ == "__main__":
                        raise SystemExit(main())
                                    

Code walkthrough

  • OllamaProvider isolates all Ollama-specific HTTP details.
  • ModelResponse normalizes provider output, including unavailable token counts as None.
  • _build_ticket_prompt() explicitly lists allowed labels and the exact JSON shape.
  • temperature=0.0 reduces randomness for a deterministic routing task.
  • json.loads() parses the response.
  • TicketClassification.model_validate() rejects labels outside the allowed set.
  • ClassificationError prevents invalid model output from entering the application workflow.

Execute

PowerShell

                                python classify_cli.py ticket "VPN connection fails after the latest client update."
                                

Expected output shape:

JSON

                                {
                    "label": "Network",
                    "reasoning": "The issue involves VPN connectivity.",
                    "latency_ms": 5124.88,
                    "input_tokens": 92,
                    "output_tokens": 24,
                    "error": null
                    }
                                

Your exact label, reasoning, latency, and token counts may differ.

PowerShell

                                python classify_cli.py error "nginx: [emerg] bind() to 0.0.0.0:80 failed (13: Permission denied)"
                                

Expected output shape:

JSON

                                {
                    "category": "Permission",
                    "reasoning": "The process lacks permission to bind to port 80.",
                    "latency_ms": 4871.20,
                    "input_tokens": 105,
                    "output_tokens": 28
                    }
                                

Zero-shot versus few-shot classification

The examples above are zero-shot: the prompt gives rules but no examples.

For a difficult or ambiguous taxonomy, add a few examples:

Examples:
Ticket: "Wi-Fi disconnects every 10 minutes."
Label: Network

Ticket: "Laptop battery does not charge."
Label: Hardware

Ticket: "Application crashes after login."
Label: Software

Few-shot examples can improve consistency, but they consume input tokens and can bias the model if the examples are unrepresentative. Use only representative, non-sensitive examples.

Multi-label classification

For multi-label classification, allow a list:

JSON

                                {
                    "labels": ["Software", "Security"],
                    "reasoning": "The application has an insecure dependency."
                    }
                                

Use a Pydantic model such as:

Python

                                from pydantic import BaseModel, Field


                    class MultiLabelClassification(BaseModel):
                        labels: list[str] = Field(min_length=0, max_length=5)
                        reasoning: str = ""
                                

Then validate each item against the allowed label set in application code.

Confidence and uncertainty

Some hosted providers can return log probabilities or confidence-related metadata; Ollama’s basic /api/generate response in this implementation does not provide a standardized confidence score. Do not invent one.

A practical Phase 1 approach is:

  • Ask the model to return confidence as high, medium, or low.
  • Treat it as a self-reported hint, not a calibrated probability.
  • Route low confidence items to human review.

Example schema:

Python

                                class TicketClassificationWithConfidence(BaseModel):
                        label: str
                        confidence: str
                        reasoning: str = ""
                                

Classification errors

Error Cause Handling
Invalid JSON Model adds prose around JSON Retry with stricter instruction; validate; log failure
Invalid label Model invents a category Reject with Pydantic; use fallback or human review
Empty response Timeout, model issue, or bad request Record provider error
Ambiguous input Ticket lacks enough information Return Unknown or route to human review
Inconsistent results Natural-language ambiguity Use lower temperature, examples, and a fixed schema

When not to use an LLM

Use deterministic rules or conventional ML when:

  • The input is structured.
  • Labels can be derived from exact fields.
  • Historical labeled data exists.
  • Latency, cost, or auditability requirements are strict.
  • The rule is simple: if "permission denied" in log: category = "Permission".

Use an LLM when phrasing varies widely and semantic interpretation is needed.

Testing

Create tests/test_classification.py:

Python

                                import pytest
                    from pydantic import ValidationError

                    from app.patterns.classification import (
                        ClassificationError,
                        _parse_model_response,
                    )
                    from app.providers.base import ModelResponse
                    from app.schemas.classification import TicketClassification


                    def test_valid_ticket_response_passes() -> None:
                        response = ModelResponse(
                            text='{"label": "Network", "reasoning": "VPN issue"}',
                            latency_ms=100.0,
                            input_tokens=20,
                            output_tokens=10,
                        )

                        result = _parse_model_response(response, TicketClassification)

                        assert result.label == "Network"


                    def test_invalid_label_fails_validation() -> None:
                        response = ModelResponse(
                            text='{"label": "Database", "reasoning": "Wrong category"}',
                            latency_ms=100.0,
                            input_tokens=20,
                            output_tokens=10,
                        )

                        with pytest.raises(ClassificationError):
                            _parse_model_response(response, TicketClassification)


                    def test_invalid_json_fails() -> None:
                        response = ModelResponse(
                            text="The correct category is Network.",
                            latency_ms=100.0,
                            input_tokens=20,
                            output_tokens=10,
                        )

                        with pytest.raises(ClassificationError):
                            _parse_model_response(response, TicketClassification)


                    def test_provider_error_is_raised() -> None:
                        response = ModelResponse(
                            text="",
                            latency_ms=0.0,
                            input_tokens=None,
                            output_tokens=None,
                            error="timeout",
                        )

                        with pytest.raises(ClassificationError):
                            _parse_model_response(response, TicketClassification)


                    def test_schema_rejects_unknown_label_directly() -> None:
                        with pytest.raises(ValidationError):
                            TicketClassification(label="Unknown")
                                

Create tests/__init__.py:

Python

                                """Test package."""
                                

Run:

PowerShell

                                pytest -v
                                

Expected:

test_classification.py::test_valid_ticket_response_passes PASSED
test_classification.py::test_invalid_label_fails_validation PASSED
test_classification.py::test_invalid_json_fails PASSED
test_classification.py::test_provider_error_is_raised PASSED
test_classification.py::test_schema_rejects_unknown_label_directly PASSED

Performance and cost

Classification prompts are usually short, but they still consume input tokens. Output should be kept small: request only the label and a brief reason.

Approach Latency Cost Quality
Rule-based Very low Near zero High for exact patterns
Conventional ML Low Low after training Depends on labeled data
Small local LLM Moderate Hardware/electricity Good for flexible phrasing
Hosted LLM Network plus inference Per-token Often higher, provider-dependent

Engineering decisionss

Use LLM classification when:

  • Wording varies substantially.
  • Categories require semantic understanding.
  • You can validate outputs.
  • Misclassification is recoverable or reviewed.

Do not use an LLM when a regex, database field, or simple rule is sufficient.

Hands-on exercise

Classify these five programming questions by topic and difficulty:

1. How do I reverse a string in Python?
2. How do I optimize a recursive Fibonacci implementation?
3. What is the difference between TCP and UDP?
4. How do I design a rate limiter for a distributed API?
5. Why does my Docker container fail to resolve DNS?

Requirements:

  • Create labels for topic and difficulty.
  • Return JSON with topic, difficulty, and reasoning.
  • Validate both fields with Pydantic.
  • Test at least one valid and one invalid response.

Acceptance criteria:

  • Invalid topic or difficulty is rejected.
  • Valid JSON produces a typed Python object.
  • The application records latency.

Review checklist

  • I can explain zero-shot and few-shot classification.
  • I can distinguish multi-class and multi-label classification.
  • I validate model output with Pydantic.
  • I know that self-reported confidence is not a calibrated probability.
  • I know when deterministic rules are preferable.
  • My tests cover valid JSON, invalid JSON, invalid labels, and provider errors.

How this contributes to a Hybrid Applied AI Systems Engineer

Classification develops intelligent automation skills. In later phases, it supports workflow routing, incident triage, content moderation, and agent decision boundaries.

You should now be able to decide independently:

  • Whether a task needs semantic classification.
  • Which labels and output schema to enforce.
  • When to route low-confidence results to a human.
  • When a rule-based or conventional ML approach is more appropriate.

Module 4 - Information extraction

Problem definition

Technical logs and support requests contain useful facts buried in unstructured text:

nginx failed to bind to 0.0.0.0:80 after configuration reload.
Error: EADDRINUSE. Process nginx version 1.24.0 is already using port 80.

An incident system may need:

JSON

                                {
                    "service": "nginx",
                    "port": 80,
                    "error_code": "EADDRINUSE",
                    "version": "1.24.0",
                    "event": "port_bind_failure"
                    }
                                

Concept explanation

Information extraction converts unstructured or semi-structured text into structured fields. Unlike classification, the output is not merely a label; it is a set of typed values.

Common extraction targets:

  • Error codes.
  • IP addresses.
  • Ports.
  • Software names.
  • Versions.
  • File paths.
  • Configuration values.
  • Usernames or ticket IDs.

Technical terminology

Term Meaning
Entity extraction Identifying named items such as service, host, or version
Field extraction Populating defined output fields
Schema Definition of required and optional fields and types
JSON mode Provider feature that encourages or enforces JSON output
Post-processing Deterministic cleanup or enrichment after model output
Exact match Extracted value equals the expected value
Field-level accuracy Percentage of individual fields extracted correctly

Why it matters

Extraction turns unstructured operational text into data that can be stored, searched, aggregated, validated, and used by other systems. It is often more valuable than a free-text answer because downstream code can act on it.

Architecture

Information extraction architecture

Execution flow

  1. Validate the input text.
  2. Build a prompt that defines every field, type, and null behavior.
  3. Send the prompt to the model.
  4. Parse the response as JSON.
  5. Validate field types and constraints using Pydantic.
  6. Apply deterministic post-processing, such as normalizing a service name or validating an IP address.
  7. Return the structured record and usage metadata.

Implementation

Create app/schemas/extraction.py:

Python

                                """Pydantic schemas for technical information extraction."""

                    import ipaddress

                    from pydantic import BaseModel, Field, field_validator


                    class LogExtraction(BaseModel):
                        service: str | None = Field(default=None, max_length=100)
                        port: int | None = Field(default=None, ge=1, le=65535)
                        error_code: str | None = Field(default=None, max_length=100)
                        ip_address: str | None = Field(default=None, max_length=45)
                        version: str | None = Field(default=None, max_length=50)
                        event: str | None = Field(default=None, max_length=200)

                        @field_validator("ip_address")
                        @classmethod
                        def validate_ip_address(cls, value: str | None) -> str | None:
                            if value is None:
                                return None
                            try:
                                ipaddress.ip_address(value)
                            except ValueError as exc:
                                raise ValueError(f"Invalid IP address: {value!r}") from exc
                            return value


                    class SoftwareExtraction(BaseModel):
                        software_name: str | None = Field(default=None, max_length=100)
                        version: str | None = Field(default=None, max_length=50)
                        configuration_key: str | None = Field(default=None, max_length=200)
                        configuration_value: str | None = Field(default=None, max_length=500)
                                

Create app/schemas/__init__.py:

Python

                                """Pydantic schema package."""

                    from app.schemas.classification import (
                        ALLOWED_ERROR_CATEGORIES,
                        ALLOWED_TICKET_LABELS,
                        ErrorClassification,
                        TicketClassification,
                    )
                    from app.schemas.extraction import LogExtraction, SoftwareExtraction

                    __all__ = [
                        "ALLOWED_ERROR_CATEGORIES",
                        "ALLOWED_TICKET_LABELS",
                        "ErrorClassification",
                        "LogExtraction",
                        "SoftwareExtraction",
                        "TicketClassification",
                    ]
                                

Create app/patterns/extraction.py:

Python

                                """LLM-based structured information extraction."""

                    import json
                    from typing import TypeVar

                    from pydantic import BaseModel, ValidationError

                    from app.providers.base import BaseModelProvider, ModelResponse
                    from app.schemas.extraction import LogExtraction, SoftwareExtraction

                    SchemaType = TypeVar("SchemaType", bound=BaseModel)


                    class ExtractionError(Exception):
                        """Raised when extraction cannot produce a valid structured result."""


                    def _build_log_prompt(text: str) -> str:
                        return (
                            "Extract technical information from the log text.\n\n"
                            "Return only valid JSON with these fields:\n"
                            "{\n"
                            '  "service": string or null,\n'
                            '  "port": integer or null,\n'
                            '  "error_code": string or null,\n'
                            '  "ip_address": string or null,\n'
                            '  "version": string or null,\n'
                            '  "event": string or null\n'
                            "}\n\n"
                            "Rules:\n"
                            "- Use null for unknown values.\n"
                            "- Do not invent values.\n"
                            "- Do not include Markdown or explanations outside JSON.\n\n"
                            f"Log:\n{text}"
                        )


                    def _build_software_prompt(text: str) -> str:
                        return (
                            "Extract software and configuration information.\n\n"
                            "Return only valid JSON with these fields:\n"
                            "{\n"
                            '  "software_name": string or null,\n'
                            '  "version": string or null,\n'
                            '  "configuration_key": string or null,\n'
                            '  "configuration_value": string or null\n'
                            "}\n\n"
                            "Rules:\n"
                            "- Use null for unknown values.\n"
                            "- Do not invent values.\n"
                            "- Return only JSON.\n\n"
                            f"Text:\n{text}"
                        )


                    def extract_structured_data(
                        provider: BaseModelProvider,
                        prompt: str,
                        schema_type: type[SchemaType],
                    ) -> tuple[SchemaType, ModelResponse]:
                        """Send an extraction prompt and validate the JSON response."""

                        response = provider.generate(prompt, temperature=0.0)

                        if response.error:
                            raise ExtractionError(f"Model request failed: {response.error}")

                        if not response.text:
                            raise ExtractionError("Model returned an empty response.")

                        try:
                            payload = json.loads(response.text)
                        except json.JSONDecodeError as exc:
                            raise ExtractionError(
                                f"Model returned invalid JSON: {response.text!r}"
                            ) from exc

                        try:
                            validated = schema_type.model_validate(payload)
                        except ValidationError as exc:
                            raise ExtractionError(
                                f"Model output failed schema validation: {exc}"
                            ) from exc

                        return validated, response


                    def extract_log_information(
                        provider: BaseModelProvider,
                        text: str,
                    ) -> tuple[LogExtraction, ModelResponse]:
                        cleaned = text.strip()

                        if not cleaned:
                            raise ExtractionError("Log text cannot be empty.")
                        if len(cleaned) > 10_000:
                            raise ExtractionError("Log text exceeds the 10,000-character limit.")

                        prompt = _build_log_prompt(cleaned)
                        return extract_structured_data(provider, prompt, LogExtraction)


                    def extract_software_information(
                        provider: BaseModelProvider,
                        text: str,
                    ) -> tuple[SoftwareExtraction, ModelResponse]:
                        cleaned = text.strip()

                        if not cleaned:
                            raise ExtractionError("Input text cannot be empty.")
                        if len(cleaned) > 10_000:
                            raise ExtractionError("Input text exceeds the 10,000-character limit.")

                        prompt = _build_software_prompt(cleaned)
                        return extract_structured_data(provider, prompt, SoftwareExtraction)
                                

Deterministic post-processing

Create app/deterministic/extractors.py:

Python

                                    """Deterministic extraction helpers that do not require an LLM."""

                    import ipaddress
                    import re

                    IPV4_PATTERN = re.compile(
                        r"\b(?:(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\.){3}"
                        r"(?:25[0-5]|2[0-4]\d|1\d\d|[1-9]?\d)\b"
                    )

                    PORT_PATTERN = re.compile(r"\b(?:port\s+|:)(\d{1,5})\b", re.IGNORECASE)


                    def extract_ipv4(text: str) -> str | None:
                        match = IPV4_PATTERN.search(text)
                        return match.group(0) if match else None


                    def extract_port(text: str) -> int | None:
                        match = PORT_PATTERN.search(text)
                        if not match:
                            return None

                        port = int(match.group(1))
                        return port if 1 <= port <= 65535 else None


                    def is_valid_ipv4(value: str) -> bool:
                        try:
                            ipaddress.IPv4Address(value)
                            return True
                        except ValueError:
                            return False
                                    

Create app/deterministic/__init__.py:

Python

                                    """Deterministic processing helpers."""
                                    

CLI command

Create extract_cli.py:

Python

                                    """Command-line interface for technical information extraction."""

                    import argparse
                    import json
                    import sys

                    from app.deterministic.extractors import extract_ipv4, extract_port
                    from app.patterns.extraction import (
                        ExtractionError,
                        extract_log_information,
                        extract_software_information,
                    )
                    from app.providers.ollama import OllamaProvider


                    def main() -> int:
                        parser = argparse.ArgumentParser(prog="extract")
                        parser.add_argument(
                            "kind",
                            choices=["log", "software"],
                            help="Type of extraction to perform.",
                        )
                        parser.add_argument("text", help="Text to process.")
                        args = parser.parse_args()

                        provider = OllamaProvider()

                        try:
                            if args.kind == "log":
                                result, response = extract_log_information(provider, args.text)
                                deterministic_ip = extract_ipv4(args.text)
                                deterministic_port = extract_port(args.text)

                                output = {
                                    "model_extraction": result.model_dump(),
                                    "deterministic_ip": deterministic_ip,
                                    "deterministic_port": deterministic_port,
                                    "latency_ms": round(response.latency_ms, 2),
                                    "input_tokens": response.input_tokens,
                                    "output_tokens": response.output_tokens,
                                }
                            else:
                                result, response = extract_software_information(provider, args.text)
                                output = {
                                    "extraction": result.model_dump(),
                                    "latency_ms": round(response.latency_ms, 2),
                                    "input_tokens": response.input_tokens,
                                    "output_tokens": response.output_tokens,
                                }

                            print(json.dumps(output, indent=2))
                            return 0

                        except ExtractionError as exc:
                            print(f"Extraction failed: {exc}", file=sys.stderr)
                            return 1


                    if __name__ == "__main__":
                        raise SystemExit(main())
                                    

Code walkthrough

  • LogExtraction defines every allowed field and type.
  • port is constrained to 1–65535.
  • ip_address is validated using Python’s ipaddress module.
  • extract_structured_data() is reusable for different extraction schemas.
  • extract_ipv4() and extract_port() demonstrate deterministic extraction.
  • The CLI compares LLM extraction with deterministic extraction for the same log.

Execute

PowerShell

                                python extract_cli.py log "nginx failed to bind to 0.0.0.0:80 after configuration reload. Error: EADDRINUSE. nginx version 1.24.0."
                                

Expected output shape:

JSON

                                {
                    "model_extraction": {
                        "service": "nginx",
                        "port": 80,
                        "error_code": "EADDRINUSE",
                        "ip_address": "0.0.0.0",
                        "version": "1.24.0",
                        "event": "port_bind_failure"
                    },
                    "deterministic_ip": "0.0.0.0",
                    "deterministic_port": 80,
                    "latency_ms": 5310.44,
                    "input_tokens": 168,
                    "output_tokens": 68
                    }
                                

PowerShell

                                python extract_cli.py software "PostgreSQL 16.2 is configured with max_connections = 100."
                                

Expected output shape:

JSON

                                {
                    "extraction": {
                        "software_name": "PostgreSQL",
                        "version": "16.2",
                        "configuration_key": "max_connections",
                        "configuration_value": "100"
                    },
                    "latency_ms": 4980.11,
                    "input_tokens": 121,
                    "output_tokens": 48
                    }
                                

Missing and ambiguous information

If the text does not contain a field, the model should return null:

JSON

                                {
                    "service": "nginx",
                    "port": null,
                    "error_code": null
                    }
                                

Do not ask the model to guess. If a field is business-critical, treat null as incomplete and route the record for review or additional processing.

Schema enforcement

Pydantic enforces:

  • Required versus optional fields.
  • Types, such as int, str, and list[str].
  • Value ranges, such as port numbers.
  • Format constraints, such as IP addresses.
  • Maximum lengths.

This is essential because an LLM may return "80" instead of 80, omit a field, or add an unexpected field.

Extraction reliability

Improve reliability by:

  • Defining every field explicitly.
  • Providing one or two short examples.
  • Setting temperature to 0.0 for deterministic extraction.
  • Requesting JSON only.
  • Validating every response.
  • Applying deterministic normalization after validation.
  • Logging failures by category.

Do not rely on prompt wording alone for production reliability.

Testing

Create tests/test_extraction.py:

Python

                                import pytest
                    from pydantic import ValidationError

                    from app.patterns.extraction import ExtractionError, _build_log_prompt
                    from app.schemas.extraction import LogExtraction


                    def test_valid_log_extraction() -> None:
                        result = LogExtraction.model_validate(
                            {
                                "service": "nginx",
                                "port": 80,
                                "error_code": "EADDRINUSE",
                                "ip_address": "0.0.0.0",
                                "version": "1.24.0",
                                "event": "port_bind_failure",
                            }
                        )

                        assert result.service == "nginx"
                        assert result.port == 80


                    def test_invalid_port_is_rejected() -> None:
                        with pytest.raises(ValidationError):
                            LogExtraction(port=99999)


                    def test_invalid_ip_is_rejected() -> None:
                        with pytest.raises(ValidationError):
                            LogExtraction(ip_address="999.999.999.999")


                    def test_missing_fields_default_to_none() -> None:
                        result = LogExtraction()

                        assert result.service is None
                        assert result.port is None


                    def test_prompt_contains_json_instruction() -> None:
                        prompt = _build_log_prompt("nginx failed to bind port 80")

                        assert "Return only valid JSON" in prompt
                        assert "nginx failed to bind port 80" in prompt


                    def test_empty_text_raises_error() -> None:
                        from app.patterns.extraction import extract_log_information
                        from app.providers.ollama import OllamaProvider

                        with pytest.raises(ExtractionError):
                            extract_log_information(OllamaProvider(), "   ")
                                

Run:

PowerShell

                                pytest -v
                                

Expected:

test_extraction.py::test_valid_log_extraction PASSED
test_extraction.py::test_invalid_port_is_rejected PASSED
test_extraction.py::test_invalid_ip_is_rejected PASSED
test_extraction.py::test_missing_fields_default_to_none PASSED
test_extraction.py::test_prompt_contains_json_instruction PASSED
test_extraction.py::test_empty_text_raises_error PASSED

Failure analysis

Failure Diagnostic Fix
Model returned invalid JSON Inspect raw response Ask for JSON only; lower temperature; use a more capable model
port returned as string Schema mismatch Use Pydantic coercion or explicitly request integer
IP validation fails Model hallucinated or malformed IP Use deterministic regex/IP validation
Missing important field Ambiguous source text Ask for null, add examples, or request human review
Slow response Long log or large local model Trim input, reduce output fields, use hosted model

Performance and cost

Extraction prompts are usually longer than classification prompts because they define a schema. Output size depends on the number of fields.

Cost-control practices:

  • Extract only fields the workflow needs.
  • Limit input length.
  • Avoid asking for explanations unless required.
  • Use a local model for sensitive or high-volume extraction when quality is acceptable.
  • Use deterministic extraction first for fields that follow fixed patterns.

Engineering decisionss

Use an LLM for extraction when:

  • Text structure varies.
  • Field names and phrasing differ.
  • Semantic interpretation is needed.
  • You can validate and review outputs.

Use regex, SQL, or conventional parsing when:

  • The pattern is fixed.
  • Input is already structured.
  • Exactness is mandatory.
  • Latency and cost must be minimal.

Hands-on exercise

Extract structured information from this support request:

User reports that the payment-service version 2.7.1 returns HTTP 502 when calling
the internal API at 10.20.30.40:8443. The error began after a certificate renewal.

Required fields:

  • service
  • version
  • http_status
  • host
  • port
  • possible_cause

Acceptance criteria:

  • port must be an integer between 1 and 65535.
  • host must be a valid IPv4 address.
  • Unknown values must be null.
  • Invalid output must raise ExtractionError.

Common mistakes:

  • Storing the port as a string.
  • Accepting an invalid IP address.
  • Asking the model to infer a cause without labeling it as uncertain.

Review guidance: Add separate Pydantic fields for http_status, host, and possible_cause. Use ipaddress.ip_address() for host validation.

Review checklist

  • I can explain entity and field extraction.
  • I can define a JSON extraction schema.
  • I validate output using Pydantic.
  • I use null for unknown values.
  • I apply deterministic post-processing where appropriate.
  • I can explain when regex is better than an LLM.
  • I can identify extraction reliability risks.

How this contributes to a Hybrid Applied AI Systems Engineer

Extraction develops structured AI data processing. It is foundational for incident-management systems, workflow automation, integrations, and knowledge-base construction.

Later phases reuse it for:

  • RAG document metadata extraction.
  • Workflow automation.
  • API integration.
  • Structured agent observations.
  • Evaluation datasets.

You should now be able to decide independently:

  • Which fields must be extracted.
  • Which fields can be null.
  • Which validations are mandatory.
  • When deterministic parsing should replace an LLM.
  • How to prevent malformed model output from entering downstream systems.

Part 2 completion checklist

  • Classification and extraction are implemented with complete Python code.
  • Provider-specific Ollama logic is separated from pattern logic.
  • Pydantic validates all structured outputs.
  • Invalid labels, invalid JSON, invalid ports, and invalid IPs are rejected.
  • Deterministic IP and port extraction is implemented.
  • Tests run successfully with pytest -v.
  • CLI commands work on Windows PowerShell.
  • Latency and token usage are captured when Ollama exposes them.
  • No secrets are hardcoded or logged.
  • You can explain when an LLM is and is not appropriate.

Module completion: Hybrid specialization connection

Concept Competency developed Future dependency
Classification Intelligent routing and decision automation Workflow automation, agents
Extraction Turning unstructured text into actionable data RAG metadata, integrations
Structured output Reliable machine-readable AI results APIs, automation, evaluation
Deterministic post-processing Trustworthy data pipelines Backend reliability, harness engineering
Latency and token tracking Cost- and performance-aware design Observability and evaluation

Part 3 - Summarization and Generation

Module 5 - Summarization

Problem definition

Technical teams need to understand long content quickly: incident logs, runbooks, README files, deployment reports, and troubleshooting guides. Reading a 5,000-word log during an incident is slow; a concise, accurate summary helps an engineer decide what to inspect next.

Example input:

The deployment failed after the PostgreSQL migration timed out. The application
could not connect to the database. The reverse proxy returned 502 errors for
approximately eight minutes. Engineers restarted the application service, verified
database connectivity, and redeployed successfully.

Desired output:

- A PostgreSQL migration timeout prevented database connectivity.
- The reverse proxy returned 502 errors for about eight minutes.
- The service recovered after restart and redeployment.

Concept explanation

Summarization transforms longer content into a shorter representation while preserving the information needed for a specific purpose.

There are two broad approaches:

Approach How it works Example
Extractive summarization Selects important sentences or phrases from the source Picks three existing sentences from an incident log
Abstractive summarization Generates new wording that conveys the source meaning Rewrites a log into three concise findings

LLMs usually perform abstractive summarization. This is flexible, but it introduces risk: the model may omit an important detail or add information that is not present in the source.

Technical terminology

Term Meaning
Extractive summary Summary composed from selected source text
Abstractive summary Summary generated in new wording
Factual consistency Summary does not contradict the source
Coverage Important source information is retained
Omission Important information is missing
Hallucination Summary contains unsupported information
Grounding Summary is constrained by provided source material
Token budget Number of input and output tokens available or allowed

Why it matters

Summarization reduces human reading time, but a bad summary can be worse than no summary. During an incident, an omitted root cause or invented remediation step can mislead responders.

Therefore, a technical summarizer should:

  • Use only supplied source text.
  • Preserve dates, error codes, services, and actions.
  • Avoid speculation.
  • Clearly indicate uncertainty.
  • Remain short enough to be useful.

Architecture

Diagram showing the architecture of a technical summarizer

For long documents, the application may need to split the source into chunks, summarize each chunk, and then combine those partial summaries. That is long-document summarization fundamentals; advanced chunking optimization belongs to the later RAG Engineering phase.

Execution flow

  1. Read or receive source text.
  2. Validate that it is non-empty and within the context budget.
  3. Build a prompt defining summary length, style, and factual constraints.
  4. Send the prompt to the model.
  5. Validate that a non-empty summary was returned.
  6. Apply deterministic checks, such as maximum length and required keyword presence where appropriate.
  7. Return the summary with latency and token metadata.

Prerequisites

You need the Part 2 project structure, active virtual environment, installed dependencies, and a working Ollama service.

Verify:

PowerShell

                                .\.venv\Scripts\Activate.ps1
                    ollama list
                    Invoke-RestMethod -Uri http://localhost:11434/api/version
                                

Implementation

Summarization schema

Create app/schemas/summarization.py:

Python

                                    """Pydantic schemas for summarization outputs."""

                    from pydantic import BaseModel, Field


                    class TechnicalSummary(BaseModel):
                        summary: str = Field(min_length=1, max_length=5_000)
                        key_points: list[str] = Field(default_factory=list, max_length=10)
                                    

Update app/schemas/__init__.py:

Python

                                    """Pydantic schema package."""

                    from app.schemas.classification import (
                        ALLOWED_ERROR_CATEGORIES,
                        ALLOWED_TICKET_LABELS,
                        ErrorClassification,
                        TicketClassification,
                    )
                    from app.schemas.extraction import LogExtraction, SoftwareExtraction
                    from app.schemas.summarization import TechnicalSummary

                    __all__ = [
                        "ALLOWED_ERROR_CATEGORIES",
                        "ALLOWED_TICKET_LABELS",
                        "ErrorClassification",
                        "LogExtraction",
                        "SoftwareExtraction",
                        "TechnicalSummary",
                        "TicketClassification",
                    ]
                                    

Summarization pattern

Create app/patterns/summarization.py:

Python

                                    """LLM-based technical summarization pattern."""

                    import json

                    from pydantic import ValidationError

                    from app.providers.base import BaseModelProvider, ModelResponse
                    from app.schemas.summarization import TechnicalSummary


                    class SummarizationError(Exception):
                        """Raised when summarization cannot produce a valid result."""


                    MAX_SOURCE_CHARACTERS = 20_000


                    def build_summary_prompt(
                        text: str,
                        style: str = "three action-oriented bullet points",
                    ) -> str:
                        return (
                            f"Summarize the following technical content as {style}.\n\n"
                            "Rules:\n"
                            "- Use only information present in the source text.\n"
                            "- Do not add assumptions, recommendations, or facts not in the source.\n"
                            "- Preserve important services, error codes, versions, ports, and actions.\n"
                            "- Return only valid JSON.\n"
                            "- Use this exact JSON shape:\n"
                            '{"summary": "<one-paragraph summary>", '
                            '"key_points": ["<point 1>", "<point 2>", "<point 3>"]}\n\n'
                            f"Source text:\n{text}"
                        )


                    def summarize_text(
                        provider: BaseModelProvider,
                        text: str,
                        style: str = "three action-oriented bullet points",
                    ) -> tuple[TechnicalSummary, ModelResponse]:
                        """Summarize technical text using a grounded, structured prompt."""

                        cleaned = text.strip()

                        if not cleaned:
                            raise SummarizationError("Source text cannot be empty.")

                        if len(cleaned) > MAX_SOURCE_CHARACTERS:
                            raise SummarizationError(
                                f"Source text exceeds the {MAX_SOURCE_CHARACTERS}-character limit. "
                                "Use chunked summarization or retrieval for longer documents."
                            )

                        prompt = build_summary_prompt(cleaned, style)
                        response = provider.generate(prompt, temperature=0.2)

                        if response.error:
                            raise SummarizationError(f"Model request failed: {response.error}")

                        if not response.text:
                            raise SummarizationError("Model returned an empty summary.")

                        try:
                            payload = json.loads(response.text)
                        except json.JSONDecodeError as exc:
                            raise SummarizationError(
                                f"Model returned invalid JSON: {response.text!r}"
                            ) from exc

                        try:
                            result = TechnicalSummary.model_validate(payload)
                        except ValidationError as exc:
                            raise SummarizationError(
                                f"Model summary failed schema validation: {exc}"
                            ) from exc

                        return result, response
                                    

Create app/utilities/latency.py:

Python

                                    """Latency measurement utilities."""

                    import time
                    from contextlib import contextmanager
                    from collections.abc import Iterator


                    @contextmanager
                    def measure_latency_ms() -> Iterator[dict[str, float]]:
                        started = time.perf_counter()
                        metrics: dict[str, float] = {"latency_ms": 0.0}

                        try:
                            yield metrics
                        finally:
                            metrics["latency_ms"] = round(
                                (time.perf_counter() - started) * 1000, 2
                            )
                                    

Create app/utilities/__init__.py:

Python

                                    """Utility package."""
                                    

CLI command

Create summarize_cli.py:

Python

                                    """Command-line interface for technical summarization."""

                    import argparse
                    import json
                    import sys
                    from pathlib import Path

                    from app.patterns.summarization import SummarizationError, summarize_text
                    from app.providers.ollama import OllamaProvider


                    def main() -> int:
                        parser = argparse.ArgumentParser(prog="summarize")
                        parser.add_argument("input_file", help="Path to a UTF-8 text file.")
                        parser.add_argument(
                            "--style",
                            default="three action-oriented bullet points",
                            help="Requested summary style.",
                        )
                        args = parser.parse_args()

                        input_path = Path(args.input_file)

                        if not input_path.exists():
                            print(f"Input file not found: {input_path}", file=sys.stderr)
                            return 1

                        try:
                            text = input_path.read_text(encoding="utf-8")
                        except UnicodeDecodeError as exc:
                            print(f"Input file must be UTF-8 encoded: {exc}", file=sys.stderr)
                            return 1

                        provider = OllamaProvider()

                        try:
                            result, response = summarize_text(provider, text, args.style)
                        except SummarizationError as exc:
                            print(f"Summarization failed: {exc}", file=sys.stderr)
                            return 1

                        print(json.dumps(
                            {
                                "summary": result.summary,
                                "key_points": result.key_points,
                                "latency_ms": round(response.latency_ms, 2),
                                "input_tokens": response.input_tokens,
                                "output_tokens": response.output_tokens,
                            },
                            indent=2,
                        ))
                        return 0


                    if __name__ == "__main__":
                        raise SystemExit(main())
                                    

Sample data

Create sample_data/incident_log.txt:

Incident timeline:

14:02 Deployment job started for payments-service version 2.7.1.
14:04 PostgreSQL migration step timed out after 300 seconds.
14:05 Application pods failed to connect to the database.
14:06 Reverse proxy began returning HTTP 502 responses.
14:08 On-call engineer inspected application logs and database connectivity.
14:11 Database connection was restored after correcting a network policy rule.
14:14 Application service was restarted.
14:18 Redeployment completed successfully.
14:20 HTTP 502 errors stopped.

Code walkthrough

  • MAX_SOURCE_CHARACTERS prevents accidentally sending an oversized document to a small local model.
  • build_summary_prompt() explicitly forbids unsupported additions.
  • The prompt requires JSON with both a paragraph summary and key points.
  • TechnicalSummary validates that the summary is non-empty and limits the number of key points.
  • summarize_text() returns both the validated result and raw operational metadata.
  • The CLI reads a UTF-8 file, which is important on Windows where default encodings can differ.

Execute

PowerShell

                                python summarize_cli.py sample_data\incident_log.txt
                                

Expected output shape:

JSON

                                {
                    "summary": "The payments-service deployment failed after a PostgreSQL migration timeout caused database connectivity issues and HTTP 502 errors. Connectivity was restored by correcting a network policy rule, after which the service was restarted and redeployed successfully.",
                    "key_points": [
                        "PostgreSQL migration timed out after 300 seconds.",
                        "The reverse proxy returned HTTP 502 responses.",
                        "The issue was resolved after correcting a network policy rule and redeploying."
                    ],
                    "latency_ms": 6820.44,
                    "input_tokens": 289,
                    "output_tokens": 94
                    }
                                

Exact wording, latency, and token counts will vary.

Long-document summarization fundamentals

If a document exceeds the context budget:

  1. Split it into overlapping or semantically coherent chunks.
  2. Summarize each chunk independently.
  3. Combine the partial summaries.
  4. Produce a final summary from the combined summaries.
Diagram illustrating the long-document summarization process

This preserves more information than truncating the document, but it can still lose cross-chunk relationships. Advanced chunking, map-reduce strategies, and retrieval-based summarization belong to later phases.

Summary evaluation

For Phase 1, evaluate summaries with:

Check Question
Factual consistency Does every claim appear in or follow directly from the source?
Coverage Are the key services, errors, and actions included?
Conciseness Is the summary materially shorter than the source?
Format compliance Does it meet the requested number of bullets or sentences?
Usefulness Can the intended reader act on it?

A simple automated check can verify that important terms appear in the summary, but keyword presence does not prove factual correctness. Human review remains necessary for qualitative quality.

Testing

Create tests/test_summarization.py:

Python

                                import pytest
                    from pydantic import ValidationError

                    from app.patterns.summarization import (
                        SummarizationError,
                        build_summary_prompt,
                        summarize_text,
                    )
                    from app.providers.base import ModelResponse
                    from app.schemas.summarization import TechnicalSummary


                    def test_valid_summary_schema() -> None:
                        result = TechnicalSummary.model_validate(
                            {
                                "summary": "Database connectivity failed during deployment.",
                                "key_points": ["Migration timed out", "Service recovered"],
                            }
                        )

                        assert result.summary.startswith("Database")
                        assert len(result.key_points) == 2


                    def test_empty_summary_is_rejected() -> None:
                        with pytest.raises(ValidationError):
                            TechnicalSummary(summary="", key_points=[])


                    def test_prompt_contains_grounding_rules() -> None:
                        prompt = build_summary_prompt("The service returned HTTP 502.")

                        assert "only information present in the source text" in prompt
                        assert "The service returned HTTP 502." in prompt


                    def test_empty_input_raises_error() -> None:
                        provider = object()

                        with pytest.raises(SummarizationError):
                            summarize_text(provider, "   ")  # type: ignore[arg-type]


                    def test_invalid_model_json_raises_error() -> None:
                        class FakeProvider:
                            def generate(self, prompt: str, temperature: float = 0.0) -> ModelResponse:
                                return ModelResponse(
                                    text="Here is the summary: the service failed.",
                                    latency_ms=100.0,
                                    input_tokens=20,
                                    output_tokens=10,
                                )

                        with pytest.raises(SummarizationError):
                            summarize_text(FakeProvider(), "The service failed.")  # type: ignore[arg-type]
                                

Run:

PowerShell

                                pytest -v
                                

Expected:

test_summarization.py::test_valid_summary_schema PASSED
test_summarization.py::test_empty_summary_is_rejected PASSED
test_summarization.py::test_prompt_contains_grounding_rules PASSED
test_summarization.py::test_empty_input_raises_error PASSED
test_summarization.py::test_invalid_model_json_raises_error PASSED

Failure analysis

Failure Likely cause Fix
Empty summary Model failure, timeout, or overly restrictive instruction Check provider response and relax output constraints
Invalid JSON Model adds prose around JSON Request JSON-only output; validate and retry
Missing key detail Summary too short or model omitted it Request specific fields, increase output allowance, or use extraction
Invented detail Hallucination Strengthen grounding instruction; use lower temperature; review output
Context exceeded Source too long Chunk, retrieve, or use a larger-context model
Slow response Large local model or long source Reduce source length, use a smaller model, or use hosted inference

Performance and cost

Summarization cost is driven by:

  • Source-document input tokens.
  • Summary output tokens.
  • Number of chunks for long documents.
  • Repeated summarization of unchanged documents.

For a local Ollama model, there is no per-token API charge, but longer inputs increase RAM use and latency. For hosted models, output-token pricing is often higher than input-token pricing, so unnecessarily verbose summaries increase cost.

Engineering decisions

Use summarization when:

  • A human needs to understand a long document quickly.
  • The source is unstructured or verbose.
  • The summary is reviewed or used as input to a human decision.

Do not use summarization when:

  • The user needs an exact record.
  • Deterministic filtering can produce the needed result.
  • The source is already short.
  • Legal, compliance, or audit requirements demand the original text.

Hands-on exercise

Create sample_data/readme.txt with a technical README of at least 300 words. Ask the model to produce:

  • One paragraph summary.
  • Exactly five key points.
  • A list of prerequisites.
  • A list of deployment steps.

Acceptance criteria:

  • Output is valid JSON.
  • Summary and key points are non-empty.
  • No more than five key points are returned.
  • Prerequisites and deployment steps are separated.
  • The application records latency and token usage.

Common mistakes:

  • Asking for too many output sections in one prompt.
  • Not validating list length.
  • Assuming the summary is factually complete without review.

Review guidance: Extend TechnicalSummary with prerequisites: list[str] and deployment_steps: list[str], then validate maximum list lengths.

Review checklist

  • I can distinguish extractive and abstractive summarization.
  • I can explain hallucination and omission risks.
  • I validate summary structure with Pydantic.
  • I know why long documents may require chunking.
  • I can explain why human review is still necessary.
  • I can estimate how source length affects latency and cost.

How this contributes to a Hybrid Applied AI Systems Engineer

Summarization develops context processing and AI productivity skills. It is reused in incident tools, document assistants, change-management systems, and RAG answer generation.

Later phases build on it through:

  • Context-window management.
  • Map-reduce document processing.
  • Retrieval-based summarization.
  • Evaluation of factual consistency.
  • Cost-aware context strategies.

Module 6 - Generation

Problem definition

Technical products often need to create content: explain an error, draft troubleshooting steps, generate documentation, produce an incident report, or create sample code.

Example request:

Explain why a reverse proxy returns HTTP 502 and list three safe diagnostic steps.

The application needs a useful technical explanation, but it must avoid presenting invented commands or unsafe actions as fact.

Concept explanation

Generation creates new text from an instruction and optional context. Unlike classification or extraction, there may be many valid outputs.

Generation can be:

Type Example
Explanation Explain what a reverse proxy does
Instructional content Generate troubleshooting steps
Documentation Generate Python function documentation
Report Generate a structured incident report
Code Generate a sample Python function

Technical terminology

Term Meaning
Prompt Instruction and context sent to the model
Temperature Sampling setting that influences output variability
Maximum output tokens Limit on generated response length
Structured generation Generating JSON or another defined format
Grounding Constraining output to supplied source material
Guardrail Application rule that limits unsafe or invalid behavior
Human approval Required review before an action is executed

Why it matters

Generation is the most flexible pattern, but also the most exposed to hallucination, unsafe advice, and inconsistent formatting. Generated technical instructions should be treated as drafts, especially when they could lead to system changes.

Architecture

AI generation architecture diagram

Execution flow

  1. Validate the user request.
  2. Add only approved context, such as documentation or prior findings.
  3. Build a prompt with role, task, constraints, and output format.
  4. Send the request to the model.
  5. Validate structure, length, and required sections.
  6. Apply safety checks for executable content.
  7. Return the generated result for display or human review.

Implementation

Generation schema

`

Create app/schemas/generation.py:

Python

                                    """Pydantic schemas for generated technical content."""

                    from pydantic import BaseModel, Field


                    class TechnicalExplanation(BaseModel):
                        title: str = Field(min_length=1, max_length=200)
                        explanation: str = Field(min_length=1, max_length=5_000)
                        diagnostic_steps: list[str] = Field(default_factory=list, max_length=10)
                        cautions: list[str] = Field(default_factory=list, max_length=10)


                    class GeneratedReport(BaseModel):
                        title: str = Field(min_length=1, max_length=200)
                        summary: str = Field(min_length=1, max_length=5_000)
                        findings: list[str] = Field(default_factory=list, max_length=20)
                        next_steps: list[str] = Field(default_factory=list, max_length=20)
                                    

Update app/schemas/__init__.py:

Python

                                    """Pydantic schema package."""

                    from app.schemas.classification import (
                        ALLOWED_ERROR_CATEGORIES,
                        ALLOWED_TICKET_LABELS,
                        ErrorClassification,
                        TicketClassification,
                    )
                    from app.schemas.extraction import LogExtraction, SoftwareExtraction
                    from app.schemas.generation import GeneratedReport, TechnicalExplanation
                    from app.schemas.summarization import TechnicalSummary

                    __all__ = [
                        "ALLOWED_ERROR_CATEGORIES",
                        "ALLOWED_TICKET_LABELS",
                        "ErrorClassification",
                        "GeneratedReport",
                        "LogExtraction",
                        "SoftwareExtraction",
                        "TechnicalExplanation",
                        "TechnicalSummary",
                        "TicketClassification",
                    ]
                                    

Generation pattern

Create app/patterns/generation.py:

Python

                                    """LLM-based technical content generation with validation."""

                    import json

                    from pydantic import ValidationError

                    from app.providers.base import BaseModelProvider, ModelResponse
                    from app.schemas.generation import GeneratedReport, TechnicalExplanation


                    class GenerationError(Exception):
                        """Raised when generation cannot produce a valid result."""


                    FORBIDDEN_COMMAND_HINTS = (
                        "rm -rf /",
                        "mkfs",
                        "dd if=",
                        "shutdown -h now",
                        "drop database",
                    )


                    def build_explanation_prompt(
                        question: str,
                        context: str | None = None,
                    ) -> str:
                        context_block = ""
                        if context:
                            context_block = f"\nUse only the following approved context:\n{context}\n"

                        return (
                            "You are a technical assistant for infrastructure and software teams.\n"
                            "Explain the user's technical question clearly and safely.\n\n"
                            "Rules:\n"
                            "- Do not invent facts, commands, version numbers, or product features.\n"
                            "- If information is missing, state what additional information is needed.\n"
                            "- Do not provide destructive commands.\n"
                            "- Return only valid JSON.\n"
                            "- Use this exact JSON shape:\n"
                            "{\n"
                            '  "title": "<short title>",\n'
                            '  "explanation": "<clear explanation>",\n'
                            '  "diagnostic_steps": ["<step 1>", "<step 2>"],\n'
                            '  "cautions": ["<caution 1>"]\n'
                            "}\n\n"
                            f"{context_block}"
                            f"Question:\n{question}"
                        )


                    def validate_generated_content(text: str) -> None:
                        """Reject clearly dangerous executable guidance."""

                        lowered = text.lower()

                        for forbidden in FORBIDDEN_COMMAND_HINTS:
                            if forbidden in lowered:
                                raise GenerationError(
                                    f"Generated content contains a forbidden command hint: {forbidden!r}"
                                )


                    def generate_explanation(
                        provider: BaseModelProvider,
                        question: str,
                        context: str | None = None,
                    ) -> tuple[TechnicalExplanation, ModelResponse]:
                        """Generate and validate a technical explanation."""

                        cleaned_question = question.strip()

                        if not cleaned_question:
                            raise GenerationError("Question cannot be empty.")

                        if len(cleaned_question) > 5_000:
                            raise GenerationError("Question exceeds the 5,000-character limit.")

                        if context and len(context) > 20_000:
                            raise GenerationError("Context exceeds the 20,000-character limit.")

                        prompt = build_explanation_prompt(cleaned_question, context)
                        response = provider.generate(prompt, temperature=0.2)

                        if response.error:
                            raise GenerationError(f"Model request failed: {response.error}")

                        if not response.text:
                            raise GenerationError("Model returned an empty response.")

                        validate_generated_content(response.text)

                        try:
                            payload = json.loads(response.text)
                        except json.JSONDecodeError as exc:
                            raise GenerationError(
                                f"Model returned invalid JSON: {response.text!r}"
                            ) from exc

                        try:
                            result = TechnicalExplanation.model_validate(payload)
                        except ValidationError as exc:
                            raise GenerationError(
                                f"Generated content failed schema validation: {exc}"
                            ) from exc

                        validate_generated_content(result.explanation)
                        validate_generated_content(" ".join(result.diagnostic_steps))

                        return result, response


                    def generate_report(
                        provider: BaseModelProvider,
                        findings: list[str],
                    ) -> tuple[GeneratedReport, ModelResponse]:
                        """Generate a structured technical report from supplied findings."""

                        if not findings:
                            raise GenerationError("At least one finding is required.")

                        cleaned_findings = [finding.strip() for finding in findings if finding.strip()]

                        if not cleaned_findings:
                            raise GenerationError("Findings cannot be empty.")

                        findings_text = "\n".join(f"- {finding}" for finding in cleaned_findings)

                        prompt = (
                            "Create a concise technical report from the following findings.\n\n"
                            "Rules:\n"
                            "- Use only the supplied findings.\n"
                            "- Do not invent root causes or remediation steps.\n"
                            "- Return only valid JSON.\n"
                            "- Use this exact JSON shape:\n"
                            "{\n"
                            '  "title": "<report title>",\n'
                            '  "summary": "<short summary>",\n'
                            '  "findings": ["<finding 1>"],\n'
                            '  "next_steps": ["<next step 1>"]\n'
                            "}\n\n"
                            f"Findings:\n{findings_text}"
                        )

                        response = provider.generate(prompt, temperature=0.2)

                        if response.error:
                            raise GenerationError(f"Model request failed: {response.error}")

                        try:
                            payload = json.loads(response.text)
                        except json.JSONDecodeError as exc:
                            raise GenerationError(
                                f"Model returned invalid JSON: {response.text!r}"
                            ) from exc

                        try:
                            result = GeneratedReport.model_validate(payload)
                        except ValidationError as exc:
                            raise GenerationError(
                                f"Generated report failed schema validation: {exc}"
                            ) from exc

                        return result, response
                                    

CLI command

Create generate_cli.py:

Python

                                    """Command-line interface for technical generation."""

                    import argparse
                    import json
                    import sys
                    from pathlib import Path

                    from app.patterns.generation import (
                        GenerationError,
                        generate_explanation,
                        generate_report,
                    )
                    from app.providers.ollama import OllamaProvider


                    def main() -> int:
                        parser = argparse.ArgumentParser(prog="generate")
                        subparsers = parser.add_subparsers(dest="command", required=True)

                        explanation = subparsers.add_parser("explanation")
                        explanation.add_argument("question")
                        explanation.add_argument("--context-file")
                        explanation.add_argument("--context")

                        report = subparsers.add_parser("report")
                        report.add_argument(
                            "findings",
                            nargs="+",
                            help="One or more findings to include in the report.",
                        )

                        args = parser.parse_args()
                        provider = OllamaProvider()

                        try:
                            if args.command == "explanation":
                                context = args.context

                                if args.context_file:
                                    context_path = Path(args.context_file)

                                    if not context_path.exists():
                                        raise GenerationError(
                                            f"Context file not found: {context_path}"
                                        )

                                    context = context_path.read_text(encoding="utf-8")

                                result, response = generate_explanation(
                                    provider, args.question, context
                                )

                                output = {
                                    "title": result.title,
                                    "explanation": result.explanation,
                                    "diagnostic_steps": result.diagnostic_steps,
                                    "cautions": result.cautions,
                                    "latency_ms": round(response.latency_ms, 2),
                                    "input_tokens": response.input_tokens,
                                    "output_tokens": response.output_tokens,
                                }

                            else:
                                result, response = generate_report(provider, args.findings)

                                output = {
                                    "title": result.title,
                                    "summary": result.summary,
                                    "findings": result.findings,
                                    "next_steps": result.next_steps,
                                    "latency_ms": round(response.latency_ms, 2),
                                    "input_tokens": response.input_tokens,
                                    "output_tokens": response.output_tokens,
                                }

                            print(json.dumps(output, indent=2))
                            return 0

                        except GenerationError as exc:
                            print(f"Generation failed: {exc}", file=sys.stderr)
                            return 1


                    if __name__ == "__main__":
                        raise SystemExit(main())
                                    

Code walkthrough

  • build_explanation_prompt() separates the role, rules, optional context, and user question.
  • validate_generated_content() is a basic Phase 1 safety check, not a complete security control.
  • The forbidden-command list is intentionally small and illustrative; production systems require broader policy controls and human approval.
  • TechnicalExplanation enforces title, explanation, and list-size constraints.
  • generate_report() restricts the model to supplied findings, reducing hallucination risk.
  • Both functions return validated Pydantic objects and provider metadata.

Execute

PowerShell

                                python generate_cli.py explanation "Why does a reverse proxy return HTTP 502?"
                                

Expected output shape:

JSON

                                {
                    "title": "HTTP 502 from a Reverse Proxy",
                    "explanation": "A reverse proxy returns HTTP 502 when it cannot obtain a valid response from the upstream application service.",
                    "diagnostic_steps": [
                        "Check whether the upstream application service is running.",
                        "Review the reverse proxy error logs.",
                        "Verify network connectivity between the proxy and upstream service."
                    ],
                    "cautions": [
                        "Do not restart services without confirming the operational impact."
                    ],
                    "latency_ms": 7412.90,
                    "input_tokens": 142,
                    "output_tokens": 118
                    }
                                

Generate a report:

PowerShell

                                python generate_cli.py report "PostgreSQL migration timed out" "Application returned HTTP 502" "Connectivity restored after network policy update"
                                

Expected output shape:

JSON

                                {
                    "title": "Deployment Connectivity Incident Report",
                    "summary": "The deployment experienced a PostgreSQL migration timeout and HTTP 502 errors. Connectivity was restored after a network policy update.",
                    "findings": [
                        "PostgreSQL migration timed out",
                        "Application returned HTTP 502",
                        "Connectivity restored after network policy update"
                    ],
                    "next_steps": [
                        "Confirm database connectivity before future deployments",
                        "Monitor reverse proxy error rates during deployment"
                    ],
                    "latency_ms": 6980.22,
                    "input_tokens": 176,
                    "output_tokens": 102
                    }
                                

Code generation fundamentals

LLMs can generate sample code, but generated code must be treated as untrusted input.

Basic rules:

  • Generate code into a review workflow, not directly into production.
  • Run generated code only in an isolated environment.
  • Never execute model-generated shell commands automatically.
  • Validate imports, syntax, and tests where appropriate.
  • Keep generated code away from credentials and secrets.
  • Require human approval for infrastructure-changing code.

A safe Phase 1 approach is to generate code as text, then require a developer to review, test, and commit it.

Temperature and generation parameters

Parameter Effect Typical use
Temperature near 0 More deterministic, focused output Extraction, classification, technical facts
Temperature around 0.2–0.7 Balanced variation Explanations, documentation
Higher temperature More varied output Creative drafting; not ideal for technical accuracy

Temperature does not guarantee identical outputs across providers, versions, or infrastructure. Treat model output as probabilistic even at low temperature.

Output validation

For generated JSON:

  • Parse with json.loads().
  • Validate with Pydantic.
  • Reject unexpected fields where the schema requires strictness.
  • Enforce maximum lengths and list sizes.
  • Check for unsafe command patterns.
  • Preserve the raw response separately for debugging, without logging secrets.

Hallucination control

Reduce hallucination by:

  • Supplying approved source context.
  • Instructing the model to state missing information.
  • Forbidding unsupported recommendations.
  • Requiring citations or source references where applicable.
  • Validating factual fields deterministically.
  • Keeping a human in the loop for consequential output.

Testing

Create tests/test_generation.py:

Python

                                import pytest
                    from pydantic import ValidationError

                    from app.patterns.generation import (
                        GenerationError,
                        build_explanation_prompt,
                        generate_explanation,
                        generate_report,
                        validate_generated_content,
                    )
                    from app.providers.base import ModelResponse
                    from app.schemas.generation import TechnicalExplanation


                    def test_valid_explanation_schema() -> None:
                        result = TechnicalExplanation.model_validate(
                            {
                                "title": "HTTP 502",
                                "explanation": "The proxy could not reach the upstream service.",
                                "diagnostic_steps": ["Check service status"],
                                "cautions": ["Review impact before restarting"],
                            }
                        )

                        assert result.title == "HTTP 502"


                    def test_empty_title_is_rejected() -> None:
                        with pytest.raises(ValidationError):
                            TechnicalExplanation(
                                title="",
                                explanation="Valid explanation",
                            )


                    def test_forbidden_command_is_rejected() -> None:
                        with pytest.raises(GenerationError):
                            validate_generated_content("Run this command: rm -rf /")


                    def test_prompt_includes_context() -> None:
                        prompt = build_explanation_prompt(
                            "Why did the deployment fail?",
                            context="The PostgreSQL migration timed out.",
                        )

                        assert "The PostgreSQL migration timed out." in prompt


                    def test_empty_question_raises_error() -> None:
                        provider = object()

                        with pytest.raises(GenerationError):
                            generate_explanation(provider, "   ")  # type: ignore[arg-type]


                    def test_report_requires_findings() -> None:
                        provider = object()

                        with pytest.raises(GenerationError):
                            generate_report(provider, [])  # type: ignore[arg-type]
                                

Run:

PowerShell

                                pytest -v
                                

Expected:

test_generation.py::test_valid_explanation_schema PASSED
test_generation.py::test_empty_title_is_rejected PASSED
test_generation.py::test_forbidden_command_is_rejected PASSED
test_generation.py::test_prompt_includes_context PASSED
test_generation.py::test_empty_question_raises_error PASSED
test_generation.py::test_report_requires_findings PASSED

Failure analysis

Failure Likely cause Fix
Invalid JSON Model adds prose or Markdown Request JSON only; validate; retry with stricter instruction
Missing sections Prompt ambiguity or output limit Define required fields explicitly; increase output allowance
Unsafe command Model generates destructive guidance Reject with policy checks; require human approval
Hallucinated facts No grounding or ambiguous question Add approved context; require uncertainty statements
Overlong response No output constraint Set maximum length and section limits
Slow response Large local model or long context Reduce context, use streaming, or use hosted inference

Performance and cost

Generation is usually more expensive than classification or extraction because output length is larger.

Cost-control practices:

  • Define a maximum response length.
  • Ask for concise sections.
  • Reuse approved context instead of regenerating it.
  • Cache deterministic results where appropriate.
  • Route simple explanations to a smaller model.
  • Reserve high-capability models for complex or high-value tasks.

Engineering decisions

Use generation when:

  • The user needs new wording or explanation.
  • The task requires flexible natural-language output.
  • A human can review the result.
  • The output does not directly trigger an unsafe action.

Do not use generation when:

  • A template with variables is sufficient.
  • The result must be exactly reproducible.
  • The task is a deterministic calculation.
  • The output will directly execute a sensitive operation without approval.

Hands-on exercise

Build a command that generates Python documentation for a supplied function.

Input:

Python

                                def divide(a: float, b: float) -> float:
                        if b == 0:
                            raise ValueError("Division by zero is not allowed.")
                        return a / b
                                

Required output JSON:

JSON

                                {
                    "function_name": "divide",
                    "purpose": "",
                    "parameters": [],
                    "returns": "",
                    "raises": [],
                    "example": ""
                    }
                                

Acceptance criteria:

  • parameters contains a and b.
  • raises contains ValueError.
  • Output validates against a Pydantic model.
  • Generated content is returned as text and is not executed.

Common mistakes:

  • Executing generated code automatically.
  • Allowing arbitrary fields.
  • Not validating that the function name matches the supplied code.

Review guidance: Use Pydantic models for Parameter, GeneratedDocumentation, and Raise. Validate that function_name == "divide" before accepting the result.

Review checklist

  • I can explain instruction-based and context-aware generation.
  • I can explain temperature and its limitations.
  • I validate generated JSON with Pydantic.
  • I understand why generated code must not be executed automatically.
  • I can identify hallucination risks.
  • I can explain when a template is better than generation.

How this contributes to a Hybrid Applied AI Systems Engineer

Generation develops AI-powered product functionality. It is the basis for documentation assistants, incident-report generators, technical support tools, and code-assistance features.

Later phases reuse it for:

  • Context-aware product features.
  • Retrieval-grounded answer generation.
  • Agent communication.
  • Report and workflow automation.
  • Safe code-assistance workflows.

You should now be able to decide independently:

  • When generation adds real product value.
  • How to constrain output format and length.
  • When human approval is required.
  • How to prevent unsafe generated content from triggering system actions.

Part 3 completion checklist

  • Summarization and generation are implemented with complete Python code.
  • Both patterns validate structured JSON using Pydantic.
  • Summarization includes grounding rules to reduce hallucination.
  • Generation includes a basic unsafe-content check.
  • CLI commands run successfully in PowerShell.
  • Tests cover valid output, invalid JSON, empty input, and unsafe content.
  • Latency and token usage are recorded when available.
  • You can explain extractive versus abstractive summarization.
  • You can explain why generated code requires review.
  • You understand when templates or deterministic code are preferable.

Module completion: Hybrid specialization connection

Concept Competency developed Future dependency
Summarization Context compression and technical communication RAG, document assistants
Long-document handling Context-window awareness Advanced RAG and retrieval
Generation AI-powered product functionality Product features and agents
Structured generation Reliable machine-readable output Workflow automation and APIs
Safety checks Controlled AI behavior Guardrails and production reliability

Conclusion

Parts 1–3 establish the core foundations of AI application engineering. You explored the architecture of LLM-powered applications, implemented classification and information extraction, and learned how to use summarization and generation for practical tasks. These concepts provide a foundation for building structured, reliable Python applications powered by LLMs.

What's Next?

The next three parts move beyond basic LLM interactions and introduce more advanced application patterns:

  • Part 4 - Embeddings and Semantic Similarity: Learn how text embeddings represent meaning as vectors, implement cosine similarity, and build a basic semantic search system.
  • Part 5 - Retrieval-Augmented Generation (RAG): Understand Retrieval-Augmented Generation (RAG) and build a workflow that ingests documents, creates chunks, retrieves relevant information, and generates context-grounded responses.
  • Part 6 - Tool Usage and Control: Learn how LLMs identify and request tools, validate arguments, and use application-controlled execution to perform bounded tasks safely.