LLM Inference Engine (chapter 7): LLM-Based AI System

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:

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:

ComponentPurposeExample
System PromptDefines the AI’s role, behavior, constraints, and instructions.Tell the model to act as a cybersecurity expert.
Conversation ManagerMaintains conversation history and contextual information across interactions.Remember previous questions and answers.
Context ManagerSelects, 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 ModelConverts text into numerical vectors for semantic similarity search.Find documents related to a user’s question.
Vector DatabaseStores and retrieves vector representations of documents.FAISS, ChromaDB.
Tool CallingAllows the LLM to invoke external functions and services.Search the web, execute code, query databases.
Agent OrchestratorCoordinates multi-step tasks, tool execution, and interactions between models.Research a topic, collect information, and produce a report.
Memory SystemStores relevant information for reuse across conversations.Remember user preferences and previous decisions.
GuardrailsEnforces safety policies and validates inputs and outputs.Prevent certain unsafe responses or actions.
Content FiltersDetects harmful, inappropriate, or policy-violating content.Detect malicious prompts or prohibited content.
Output ParserConverts generated responses into structured formats.JSON, XML, database records.
Model RouterSelects an appropriate model based on task complexity or requirements.Use a smaller model for classification and a larger one for reasoning.
Evaluation SystemMeasures 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:

ComponentRecommended toolResponsibility
Model runtimeOllamaRun LLMs
API gatewayLiteLLMManage model APIs
Application frameworkLangChainConnect application components
Agent orchestrationLangGraphManage multi-step execution
Document processingDoclingExtract document content
EmbeddingsSentence TransformersGenerate embeddings
Vector databaseQdrantStore and retrieve vectors
MemoryMem0Retain user information
GuardrailsLLM GuardSecurity validation
ObservabilityLangfuseTrace and monitor execution
EvaluationRagasEvaluate RAG quality
FrontendOpen WebUIProvide 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:

  1. Frontend (Open WebUI): Receives the user’s prompt and sends it to the backend.
  2. Conversation Manager: Retrieves previous messages to provide conversational context.
  3. Memory (Mem0): Retrieves relevant long-term user information and preferences.
  4. Orchestrator (LangGraph): Determines which components and operations are needed to answer the question.
  5. Document Processing (Docling): Previously extracts and converts uploaded documents into searchable text chunks.
  6. Embedding Model (Sentence Transformers): Converts the user’s question into a numerical vector for semantic search.
  7. Vector Database (Qdrant): Finds relevant passages from the internal security handbook.
  8. Context Manager: Combines the original question, conversation history, memory, and retrieved documents into a model-ready context.
  9. Model Gateway (LiteLLM): Routes the inference request to the selected LLM runtime.
  10. LLM Runtime (Ollama): Loads the model and executes inference to generate a response.
  11. Tool Calling (External APIs): If necessary, allows the LLM to request external information or execute authorized operations.
  12. Guardrails (LLM Guard): Checks generated content against security policies and validation rules.
  13. Output Parser: Converts the response into the required format, such as structured JSON or formatted text.
  14. Frontend (Open WebUI): Displays the final response to the user.
  15. Observability (Langfuse): Records execution traces, token usage, latency, and errors for debugging and monitoring.
  16. 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:

Leave a Reply