Assuming that we already know how to build a decoder-only Transformer architecture and understand how it works internally, the next step is to apply its token-generating capabilities to solve a real-world problem. Instead of writing code from scratch and keeping things practical, we will use Ollama as our inference engine. Ollama solves the challenges we encountered in previous chapters and provides an HTTP interface for receiving prompts, but that does not mean it will automatically be useful right away. Previous chapters are listed as below:
- LLM Inference Engine (chapter 1): Transformer Architecture From Scratch – GGUF Format
- LLM Inference Engine (chapter 2): Transformer Architecture From Scratch – Tokenization
- LLM Inference Engine (chapter 3): Transformer Architecture From Scratch – Token Embedding
- LLM Inference Engine (chapter 4): Transformer Architecture From Scratch – Attention Scores
- LLM Inference Engine (chapter 5): Transformer Architecture From Scratch – Feed Forward Sub-Layer
- LLM Inference Engine (chapter 6): Transformer Architecture From Scratch – Next Token Prediction
As we have noted, the underlying mechanism of LLM-based AI is fundamentally mathematical. Each generated token is selected based on probability distributions calculated by the model. (See LLM Inference Engine (chapter 6): Transformer Architecture From Scratch – Next Token Prediction). Understanding this nature may help us use AI more cautiously instead of trusting its answers completely. In fact, without the systems built around the inference engine, LLMs themselves may appear far less intelligent than the experiences we have with ChatGPT, Claude, or Gemini. These products are not simply standalone language models; they combine LLMs with additional components, such as system instructions, conversation management, external tools, retrieval mechanisms, and other orchestration layers.
By their nature, LLMs are trained to predict and generate human-like language based on patterns learned from training data. Although they can encode factual knowledge and exhibit reasoning-like capabilities, they do not inherently guarantee factual accuracy, logical consistency, or systematic thinking. Much of the intelligence we experience in modern AI products comes from how the underlying models are integrated into larger systems. Here we call the system around an inference engine is LLM-based AI System.
1. LLM-Based AI System
Below are the components that every AI system contains:
| Component | Purpose | Example |
|---|---|---|
| System Prompt | Defines the AI’s role, behavior, constraints, and instructions. | Tell the model to act as a cybersecurity expert. |
| Conversation Manager | Maintains conversation history and contextual information across interactions. | Remember previous questions and answers. |
| Context Manager | Selects, organizes, and manages information passed into the model’s context window. | Prioritize relevant conversation history. |
| RAG (Retrieval-Augmented Generation) | Retrieves external knowledge to supplement the model’s training knowledge. | Search internal documents before answering. |
| Embedding Model | Converts text into numerical vectors for semantic similarity search. | Find documents related to a user’s question. |
| Vector Database | Stores and retrieves vector representations of documents. | FAISS, ChromaDB. |
| Tool Calling | Allows the LLM to invoke external functions and services. | Search the web, execute code, query databases. |
| Agent Orchestrator | Coordinates multi-step tasks, tool execution, and interactions between models. | Research a topic, collect information, and produce a report. |
| Memory System | Stores relevant information for reuse across conversations. | Remember user preferences and previous decisions. |
| Guardrails | Enforces safety policies and validates inputs and outputs. | Prevent certain unsafe responses or actions. |
| Content Filters | Detects harmful, inappropriate, or policy-violating content. | Detect malicious prompts or prohibited content. |
| Output Parser | Converts generated responses into structured formats. | JSON, XML, database records. |
| Model Router | Selects an appropriate model based on task complexity or requirements. | Use a smaller model for classification and a larger one for reasoning. |
| Evaluation System | Measures response quality, accuracy, and consistency. | Automated tests and LLM-as-a-judge. |
These components form an architecture like this:
USER
|
v
APPLICATION INTERFACE
|
v
CONVERSATION MANAGER
|
v
AI ORCHESTRATOR
|
+--------+--------+
| | |
v v v
MEMORY RAG TOOL CALLING
| | |
v v v
Database Vector DB External APIs
|
v
LLM INFERENCE
|
v
OUTPUT PARSER
|
v
GUARDRAILS
|
v
USER RESPONSE
This is a conceptual architecture. In practice, the orchestrator may invoke the LLM multiple times, retrieve information, execute tools, and validate intermediate results before producing the final response.
2. Open-source AI Stack
Building an LLM-Based AI System does not require developing every component from scratch. There is already a mature open-source ecosystem covering model inference, memory, knowledge retrieval, agent orchestration, security, and evaluation. Below is a list of tools that we will use in next chapters:
| Component | Recommended tool | Responsibility |
|---|---|---|
| Model runtime | Ollama | Run LLMs |
| API gateway | LiteLLM | Manage model APIs |
| Application framework | LangChain | Connect application components |
| Agent orchestration | LangGraph | Manage multi-step execution |
| Document processing | Docling | Extract document content |
| Embeddings | Sentence Transformers | Generate embeddings |
| Vector database | Qdrant | Store and retrieve vectors |
| Memory | Mem0 | Retain user information |
| Guardrails | LLM Guard | Security validation |
| Observability | Langfuse | Trace and monitor execution |
| Evaluation | Ragas | Evaluate RAG quality |
| Frontend | Open WebUI | Provide a chat interface |
Then the architecture becomes:
USER
|
v
FRONTEND
Open WebUI
|
v
APPLICATION API
|
v
LLM ORCHESTRATOR
LangGraph
|
+------------+------------+
| | |
v v v
MEMORY RAG TOOL CALLING
Mem0 Qdrant External APIs
^
|
EMBEDDINGS
Sentence Transformers
^
|
DOCUMENTS
Docling
|
v
MODEL GATEWAY
LiteLLM
|
v
MODEL RUNTIME
Ollama
|
v
LLM MODEL
+----------------------------+
| SECURITY & QUALITY |
| |
| LLM Guard |
| Langfuse |
| Ragas |
+----------------------------+
Let’s walk through a practical example to understand how a prompt travels through an LLM-based AI system. Imagine you build a Cybersecurity AI Assistant using above open-source stack. You upload security documentation, vulnerability reports, and internal incident-response procedures. Users can ask questions about these materials: “Based on our internal security handbook, how should we respond if a production server is suspected of being compromised?”. Then the AI System performs below steps:
- Frontend (Open WebUI): Receives the user’s prompt and sends it to the backend.
- Conversation Manager: Retrieves previous messages to provide conversational context.
- Memory (Mem0): Retrieves relevant long-term user information and preferences.
- Orchestrator (LangGraph): Determines which components and operations are needed to answer the question.
- Document Processing (Docling): Previously extracts and converts uploaded documents into searchable text chunks.
- Embedding Model (Sentence Transformers): Converts the user’s question into a numerical vector for semantic search.
- Vector Database (Qdrant): Finds relevant passages from the internal security handbook.
- Context Manager: Combines the original question, conversation history, memory, and retrieved documents into a model-ready context.
- Model Gateway (LiteLLM): Routes the inference request to the selected LLM runtime.
- LLM Runtime (Ollama): Loads the model and executes inference to generate a response.
- Tool Calling (External APIs): If necessary, allows the LLM to request external information or execute authorized operations.
- Guardrails (LLM Guard): Checks generated content against security policies and validation rules.
- Output Parser: Converts the response into the required format, such as structured JSON or formatted text.
- Frontend (Open WebUI): Displays the final response to the user.
- Observability (Langfuse): Records execution traces, token usage, latency, and errors for debugging and monitoring.
- Evaluation (Ragas / DeepEval): Tests answer quality, retrieval accuracy, and consistency to help developers improve the system.
3. Next Steps
Here, we already have a brief list of what to build next. In the next chapters, we will dive into each component.
Learn more about AI:
