Introduction: Stop Building Everything as a Chatbot
Have you ever tried building an AI-powered application and ended up putting everything into one large prompt?
You need to classify support tickets, extract information from documents, summarize application logs, search internal knowledge, or execute an application-level action.
Your first thought might be: Can an LLM handle all of this?
Technically, an LLM can attempt many of these tasks. But a reliable AI application requires more than sending prompts and displaying responses.
The better approach is to understand AI application patterns.
An AI application pattern is a repeatable architectural approach for solving a particular category of problem using an AI model.
In this tutorial, we'll explore seven essential patterns:
- Classification
- Information Extraction
- Text Summarization
- Content Generation
- Embeddings and Semantic Similarity
- Retrieval-Augmented Generation (RAG)
- Tool Calling
We'll also explore how to combine these patterns with deterministic Python programming to build more reliable AI applications.
By the end, you'll understand how to structure an LLM-powered Python application instead of treating every AI feature as another chatbot.
Source: DevSpireHub – AI Patterns: Practical Tutorial for Building AI Applications with Python
1. Understand the Common LLM Application Architecture
Before implementing individual patterns, understand where an LLM belongs in your application.
A typical LLM application follows this execution flow:
User Input
|
Input Validation
|
Prompt Construction
|
Model Request
|
Model Response
|
Output Validation
|
Application Result
Error handling and observability support the entire workflow.
Each component has a separate responsibility:
| Component | Responsibility |
|---|---|
| User Interface | Collect input and display results |
| Application Logic | Manage workflows and business rules |
| Prompt Builder | Construct model instructions |
| Provider Adapter | Communicate with the model |
| Model | Generate responses |
| Output Validator | Enforce expected structure |
| Observability | Record metrics and errors |
The important engineering principle is that the model should not control your entire application.
For example, the LLM generates a response, but your Python application decides whether that response is valid.
2. Classification and Information Extraction
These two patterns are useful when working with support tickets, incident reports, application logs, and other unstructured text.
Pattern 1: Classification
Classification assigns predefined categories to an input.
For example:
Input:
"VPN connection fails after the latest update."
Output:
Network
A reliable classifier should use an application-defined set of allowed labels rather than accepting arbitrary model responses.
Python implementation using Pydantic:
from typing import Literalfrom pydantic import BaseModelclass TicketClassification(BaseModel): category: Literal[ "Network", "Hardware", "Software", "Security" ]def validate_classification(data: dict): return TicketClassification.model_validate(data)result = validate_classification({ "category": "Network"})print(result.category)
This approach ensures that the returned category belongs to your predefined taxonomy.
Pattern 2: Information Extraction
Information extraction converts unstructured text into structured fields.
Consider this application log:
nginx failed to bind to port 80.
Error: EADDRINUSE.
Version: 1.24.0
The desired output is:
{
"service": "nginx",
"port": 80,
"error_code": "EADDRINUSE",
"version": "1.24.0"
}
Python implementation:
from pydantic import BaseModel, Fieldclass LogExtraction(BaseModel): service: str | None = None port: int | None = Field( default=None, ge=1, le=65535 ) error_code: str | None = None version: str | None = Nonedata = { "service": "nginx", "port": 80, "error_code": "EADDRINUSE", "version": "1.24.0"}result = LogExtraction.model_validate(data)print(result.model_dump())
Engineering takeaway: Classification produces labels, while extraction produces structured data. Both require output validation before downstream processing.
3. Summarization and Content Generation
These patterns solve two different problems: reducing existing information and creating new information.
Pattern 3: Text Summarization
Technical teams frequently work with lengthy application logs, deployment reports, README files, and incident documentation.
Summarization helps convert this information into concise findings.
Example:
Input:
The PostgreSQL migration timed out.
The application could not connect to
the database. The reverse proxy returned
502 errors for approximately eight minutes.
Expected output:
1. PostgreSQL migration timed out.
2. Database connectivity was interrupted.
3. Reverse proxy returned HTTP 502 errors.
4. The incident lasted approximately 8 minutes.
Python prompt construction:
def build_summary_prompt(text: str) -> str: return f""" Summarize this technical incident. Requirements: - Return exactly 4 bullet points. - Preserve important technical details. - Do not invent information. - Mention errors and recovery details. Incident: {text} """
The model generates the summary, while your application handles input validation and output checks.
Pattern 4: Content Generation
Generation creates new content using instructions, context, and constraints.
For example, a developer might need troubleshooting documentation for an HTTP 502 error.
def build_generation_prompt(issue: str) -> str: return f""" Act as a technical documentation assistant. Explain the following issue: {issue} Include: 1. Possible causes. 2. Safe diagnostic steps. 3. Suggested troubleshooting guidance. Do not invent commands or claim that unverified actions are safe. """
Example input:
Explain why a reverse proxy returns HTTP 502.
Expected output: A structured technical explanation containing possible causes and diagnostic steps.
Engineering takeaway: Summarization preserves and condenses existing information. Generation produces new content, which may require additional review for accuracy and safety.
4. Embeddings and Retrieval-Augmented Generation (RAG)
These patterns are particularly important when building semantic search engines and knowledge assistants.
Pattern 5: Embeddings and Semantic Similarity
Traditional keyword search looks for matching words.
Semantic search attempts to identify similar meaning.
For example:
Text A:
Cannot connect to database.
Text B:
Database connection failure.
The wording differs, but both describe a similar problem.
Embeddings represent text as numerical vectors. Similarity measurements can then compare those vectors.
Python implementation using cosine similarity:
import mathdef cosine_similarity(a, b): dot = sum(x * y for x, y in zip(a, b)) norm_a = math.sqrt(sum(x * x for x in a)) norm_b = math.sqrt(sum(y * y for y in b)) if norm_a == 0 or norm_b == 0: return 0.0 return dot / (norm_a * norm_b)vector_a = [0.8, 0.2, 0.5]vector_b = [0.7, 0.3, 0.6]score = cosine_similarity(vector_a, vector_b)print(round(score, 4))
The vectors above are illustrative. In a real application, generate them using an embedding model.
Pattern 6: Retrieval-Augmented Generation (RAG)
An LLM does not automatically know the contents of your private documentation or internal knowledge base.
RAG addresses this by retrieving relevant information and providing it to the model as context.
A basic workflow:
User Question
|
Document Retrieval
|
Relevant Context
|
LLM
|
Grounded Answer
Minimal Python retrieval example:
documents = [ "PostgreSQL migration failed due to timeout.", "Nginx returned EADDRINUSE on port 80.", "VPN connection failed after client update."]def retrieve_documents(query: str): keywords = set(query.lower().split()) results = [ doc for doc in documents if keywords.intersection( set(doc.lower().split()) ) ] return resultsquestion = "PostgreSQL migration timeout"context = retrieve_documents(question)print(context)
This is a simple keyword-based retrieval demonstration, not a complete semantic RAG implementation.
A full RAG pipeline adds document ingestion, chunking, embeddings, similarity-based retrieval, context construction, and grounded answer generation.
Engineering takeaway: Embeddings help find semantically related information. RAG uses retrieval to provide relevant context for LLM-generated answers.
5. Tool Calling and Deterministic Engineering
Pattern 7: Tool Calling
Sometimes an AI application needs more than generating text.
It might need to check service status, retrieve information from an API, or perform an approved operation.
Tool calling allows the model to request an application-level tool.
However, the application must validate the request and execute the actual operation.
Example implementation:
def get_service_status(service: str): allowed_services = { "nginx": "running", "postgresql": "running" } if service not in allowed_services: raise ValueError("Unknown service") return allowed_services[service]# Simulated validated tool requesttool_request = { "name": "get_service_status", "arguments": { "service": "nginx" }}if tool_request["name"] == "get_service_status": result = get_service_status( **tool_request["arguments"] ) print(result)
This demonstrates application-side tool execution. In a real tool-calling integration, the model proposes the tool name and arguments, and the application validates them before dispatching.
Never allow arbitrary model-generated commands to execute directly on your system.
Deterministic Programming vs. LLM
One of the most important lessons in AI engineering is knowing when not to use an LLM.
| Deterministic Python | LLM-based tasks |
|---|---|
| Input validation | Natural-language classification |
| Business rules | Ambiguous extraction |
| Database access | Summarization |
| Mathematical calculations | Explanation generation |
| File and API access | Semantic matching |
| Output formatting | Contextual content generation |
For example, if you need to validate an IP address, use Python:
import ipaddressdef validate_ip(value: str) -> bool: try: ipaddress.ip_address(value) return True except ValueError: return Falseprint(validate_ip("192.168.1.1"))
There is no reason to call an LLM for this predictable operation.
The principle: Use deterministic code for predictable operations and LLMs for tasks involving language and semantic understanding.
Bonus: Building a Reliable Python AI Development Environment
The DevSpireHub tutorial uses Python, Pydantic, HTTPX, python-dotenv, pytest, and Ollama for its practical implementation.
Create your environment:
python -m venv .venv
.\.venv\Scripts\Activate.ps1
python -m pip install --upgrade pip
pip install httpx pydantic python-dotenv pytest
For local model inference, install and configure Ollama separately.
Verify the service:
ollama --version
ollama list
Invoke-RestMethod `
-Uri http://localhost:11434/api/version
Do not expose the local Ollama service to the public internet.
Recommended project structure
technical-ai-patterns-lab/
│
├── main.py
├── .env.example
├── requirements.txt
│
├── app/
│ ├── providers/
│ │ ├── base.py
│ │ ├── ollama.py
│ │ └── hosted.py
│ │
│ ├── patterns/
│ │ ├── classification.py
│ │ ├── extraction.py
│ │ ├── summarization.py
│ │ ├── generation.py
│ │ ├── similarity.py
│ │ ├── rag.py
│ │ └── tool_calling.py
│ │
│ ├── schemas/
│ ├── deterministic/
│ └── utilities/
│
└── tests/
├── test_classification.py
├── test_extraction.py
└── test_deterministic.py
Keep the initial architecture simple. Add vector databases, orchestration frameworks, or additional infrastructure only when your application requires them.
Final Thoughts: Build AI Applications, Not Just AI Prompts
Understanding AI application patterns changes how you approach software development.
Instead of treating every problem as a prompt-engineering challenge, identify the actual requirement and select the appropriate pattern.
Remember these five engineering principles:
- Choose the right AI pattern for the problem.
- Validate model-generated structured outputs.
- Use embeddings and retrieval when semantic search is required.
- Keep tool execution under application control.
- Prefer deterministic Python code for predictable operations.
An LLM should be treated as a probabilistic component inside a larger software system, not as a replacement for application architecture.
The goal is not simply to integrate an AI model. It is to build an AI application that is maintainable, testable, observable, and reliable.
Continue Learning with DevSpireHub
Want to build practical AI applications using Python?
Explore the complete tutorial:
AI Patterns: Practical Tutorial for Building AI Applications with Python
You'll find hands-on implementations, architecture explanations, testing exercises, and practical engineering guidance.
If you found this useful:
- Bookmark this article for your next AI project.
- Share your experience implementing RAG, embeddings, or tool calling in the comments.
- Follow DevSpireHub for practical AI engineering tutorials, Python development guides, and open-source developer resources.
DevSpireHub: Learn. Build. Grow.
Website: https://devspirehub.com
Source reference: DevSpireHub, AI Patterns: Practical Tutorial for Building AI Applications with Python. The examples above are concise teaching demonstrations based on the tutorial's architecture and implementation approach; they are not a replacement for its complete runnable project.

Top comments (1)
tickets classify