# Generative AI Fundamentals for Java Developers: A Deep Dive into LLMs, RAG, Embeddings & Spring AI, Before Building Spring Boot AI Applications

## 1\. Introduction

Generative AI is changing how we build software applications.

Traditionally, backend applications followed predefined business logic:

1. Receive a request.
2. Validate the input.
3. Execute business logic.
4. Fetch or update data.
5. Return a response.

With Generative AI, applications can do much more. They can understand natural language, summarize documents, answer questions, generate content and interact with external tools.

For Java developers, this creates an opportunity to combine existing backend engineering skills with AI capabilities.

But before building an AI-powered application using Java and Spring Boot, we need to understand some fundamental concepts.

In this article, we'll explore the essential concepts of Generative AI, understand how LLMs work at a high level, and see how these concepts connect to Spring AI.

By the end, you'll understand the building blocks required to start developing an enterprise-grade Generative AI application using Java and Spring Boot.

### What you'll learn

- Artificial Intelligence, Machine Learning and Deep Learning
- Generative AI and Large Language Models
- Foundation models and prompt engineering
- Tokens, tokenization and embeddings
- Transformers, attention and inference
- Hallucinations and Retrieval-Augmented Generation
- Tool calling and AI agents
- Ollama and Spring AI
- Enterprise GenAI architecture
- A practical learning roadmap and interview questions

### Quick Overview: What Is Generative AI for Java Developers?

Generative AI enables applications to generate content such as text, code, images and answers using AI models.

For Java developers, frameworks such as Spring AI make it possible to integrate Large Language Models, embeddings, Retrieval-Augmented Generation (RAG) and AI agents into Spring Boot applications.

The goal is to combine AI capabilities with existing backend technologies, databases, APIs and enterprise business logic.

## 2\. What Is Artificial Intelligence (AI)?

Artificial Intelligence is the ability of machines or computer systems to perform tasks that normally require human intelligence.

Examples include:

- Understanding language.
- Recognizing images.
- Making predictions.
- Identifying patterns.
- Solving problems.

For example, a traditional application might check whether an order amount is greater than ₹10,000 using a predefined condition.

An AI system might analyze historical transaction patterns to identify unusual activity.

## 3\. AI vs Machine Learning vs Deep Learning vs Generative AI

These terms are related, but they are not the same.

| Concept | Meaning | Example |
| --- | --- | --- |
| Artificial Intelligence (AI) | Broad field of creating intelligent systems | Virtual assistants |
| Machine Learning (ML) | Systems learn patterns from data | Fraud detection |
| Deep Learning (DL) | Uses multi-layer neural networks to learn complex patterns | Image recognition |
| Generative AI (GenAI) | Generates new content based on learned patterns | ChatGPT and code generation |

### Understanding the relationship

- **Artificial Intelligence:** The broader field.
- **Machine Learning:** A subset of AI that learns patterns from data.
- **Deep Learning:** A subset of ML that uses multi-layer neural networks.
- **Generative AI:** AI that generates new content. Many modern GenAI systems use deep learning, but GenAI is not simply another nested category in every technical classification.

The relationship can be represented as:

![](https://cdn.hashnode.com/uploads/covers/688293ee74301582de5306c3/a029844a-a26c-4563-936f-188027fc5f14.png align="center")

This is a simplified conceptual view. Generative AI is not limited to one particular model architecture.

## 4\. What Is Generative AI?

Generative AI refers to AI systems that create new content based on the input they receive.

It can generate:

- Text and code.
- Images.
- Audio and speech.
- Summaries.
- Explanations.
- Structured data.

For example, we can ask an AI model:

"Create a Spring Boot REST API for managing employees."

The model can generate Java classes, controllers, services and repository examples based on that instruction.

Unlike traditional applications that follow only predefined response logic, Generative AI can produce different responses based on the prompt and context.

### Traditional Programming vs Generative AI

| Traditional Programming | Generative AI |
| --- | --- |
| Follows predefined instructions | Generates responses based on learned patterns |
| Usually deterministic for the same input and state | May produce different responses |
| Business rules are explicitly implemented | Model behavior is influenced by prompts and training |
| Best suited for predictable workflows | Useful for language, content and reasoning-like tasks |

**Important:** Generative AI does not replace traditional programming. Enterprise applications often combine deterministic business logic with AI-generated capabilities.

## 5\. What Is a Large Language Model (LLM)?

LLM stands for Large Language Model.

An LLM is an AI model trained on large amounts of data to understand and generate language.

Examples include:

- OpenAI GPT models.
- Google Gemini.
- Anthropic Claude.
- Meta Llama.
- Alibaba Qwen.

An LLM can perform tasks such as:

- Answering questions.
- Summarizing documents.
- Generating code.
- Translating languages.
- Explaining technical concepts.
- Extracting information from text.

### How does an LLM work?

At a high level, an LLM predicts the next token based on the tokens it has already received.

For example:

```text
Input:
Java is a ______

Possible next token:
programming
```

The model predicts a likely next token and continues generating tokens until it reaches a stopping condition.

Actual LLMs use neural network architectures and complex mathematical operations to generate responses.

### Simple LLM workflow

1. Receive the input prompt.
2. Convert the text into tokens.
3. Process the tokens through the model.
4. Predict the next token.
5. Continue generating tokens.
6. Return the generated response.

**Java developer perspective:** Think of an LLM as a language-generation component that your application can communicate with through an API.

## 6\. What Is a Foundation Model?

A foundation model is a model trained on broad datasets that can be adapted to perform many different tasks.

Instead of building a separate model from scratch for every use case, developers can use an existing foundation model and guide it through prompts, additional training or other techniques.

For example, a general-purpose language model can be used for:

- Customer support.
- Document summarization.
- Code generation.
- Knowledge assistants.
- Information extraction.

An LLM is a common type of foundation model.

**Simple difference:**

A foundation model is a broadly trained model that can support different applications. An LLM is a foundation model designed primarily for language-related tasks.

## 7\. What Is a Prompt?

A prompt is the instruction or input we provide to an AI model.

For example:

```text
Explain Java HashMap in simple words.
```

The model uses this prompt as context to generate a response.

Prompts can contain instructions, questions, context, examples and formatting requirements.

### Common prompt types

**System prompt:** Defines the model's role, behavior and instructions.

```text
You are an experienced Java backend developer.
Explain concepts using simple language and practical examples.
```

**User prompt:** Contains the actual question or task.

```text
Explain how HashMap works internally in Java.
```

**Context:** Additional information provided to help the model answer.

```text
Use Java 21 and Spring Boot examples.
```

### What is Prompt Engineering?

Prompt engineering is the practice of designing clear instructions and providing useful context so that an AI model produces more relevant and consistent responses.

A good prompt generally includes:

- A clear task.
- Relevant context.
- Expected output format.
- Constraints.
- Examples when necessary.

**Weak prompt:**

Explain Java.

**Better prompt:**

Explain Java HashMap internals using Java 21. Cover hashing, buckets, collisions and resizing. Include a simple code example and explain the time complexity.

We'll explore prompt engineering with practical Java examples in a separate article.

## 8\. What Are Tokens and Tokenization?

An LLM does not directly process human-readable sentences in the same way humans do.

Text is first divided into smaller units called tokens.

A token can represent:

- A complete word.
- Part of a word.
- Punctuation.
- A number.
- A special model token.

This process is called tokenization.

For example:

```text
Input:
I love Java programming.

Illustrative tokens:
["I", "love", "Java", "programming", "."]
```

Actual token boundaries depend on the model's tokenizer. A token is not necessarily one complete word.

Tokens are important because they influence input and output usage, context window limits, model performance and hosted-model usage costs.

### What are Token IDs?

After tokenization, tokens are mapped to numerical identifiers called token IDs.

For example, a tokenizer might represent a sentence internally as a sequence of integer IDs.

These IDs are model-specific. They are not universal word numbers.

### Why are tokens important?

Tokens influence:

1. **Input usage:** How much text is sent to the model.
2. **Output usage:** How much text the model generates.
3. **Context window:** How much information the model can process in a request.
4. **Cost:** Hosted AI providers often charge based on token usage.
5. **Performance:** Longer prompts can increase processing time.

We'll explore token IDs, input/output tokens, Tokens Per Second (TPS) and Time to First Token (TTFT) in a dedicated article.

## 9\. What Are Embeddings?

Embeddings are numerical vector representations of data, such as text.

They help represent semantic meaning so that similar content can be compared mathematically.

Consider these sentences:

```text
Sentence 1:
How can I reset my password?

Sentence 2:
I forgot my password. How do I change it?
```

Although the sentences use different words, their meanings are similar.

An embedding model can convert both sentences into numerical vectors that are close to each other in vector space.

Illustrative example:

Sentence 1: \[0.21, 0.82, 0.43, 0.17\]

Sentence 2: \[0.23, 0.79, 0.45, 0.19\]

These are illustrative numbers, not actual model output.

Because their semantic representations are similar, a similarity-search algorithm may identify them as related.

### Keyword Search vs Semantic Search

| Keyword Search | Semantic Search |
| --- | --- |
| Matches specific words | Finds conceptually similar content |
| Depends heavily on matching terms | Uses vector representations |
| May miss differently worded questions | Can retrieve relevant meaning |
| Example: search for "password reset" | Example: find "I forgot my login password" |

### Where are embeddings used?

- Semantic search.
- Recommendation systems.
- Document similarity.
- Duplicate detection.
- Retrieval-Augmented Generation.
- Knowledge assistants.

### How do embeddings connect to RAG?

In a RAG application, documents are converted into embeddings and stored in a vector database.

When a user asks a question, the application converts that question into an embedding and searches for semantically similar document chunks.

The retrieved information is then provided to the LLM as context.

Embeddings are one of the most important building blocks of RAG.

## 10\. What Is a Transformer?

A Transformer is a neural network architecture widely used in modern language models.

It helps a model understand relationships between tokens in a sequence.

One of its important mechanisms is called **Attention**.

### What is Attention?

Attention helps the model determine which parts of the input are relevant when processing a particular token.

For example:

```text
The Java developer fixed the production issue
because he understood the root cause.
```

To interpret the sentence, the model needs to understand relationships between words and their context.

The attention mechanism helps the model calculate how much importance to assign to different tokens when processing a sequence.

### Why are Transformers important?

Transformers provide an architecture that can process relationships between tokens efficiently and learn complex language patterns.

They are widely used in modern language models and many other AI systems.

We'll explore Transformers, self-attention, inference and model architecture in a dedicated article.

## 11\. What Is Inference?

Inference is the process of using a trained model to generate predictions or responses for new input.

Training and inference are different stages.

| Training | Inference |
| --- | --- |
| Model learns patterns from data | Model uses learned patterns |
| Computationally intensive | Happens when an application requests a response |
| Updates model parameters | Normally uses the existing trained parameters |
| Usually performed before deployment or during fine-tuning | Happens during application execution |

### Example

When we send a prompt to an LLM and receive an answer, the model is performing inference.

### Simplified inference workflow

1. User sends a prompt.
2. Application sends the request to the model.
3. Model processes the input.
4. Model generates output tokens.
5. Application receives the response.

![](https://cdn.hashnode.com/uploads/covers/688293ee74301582de5306c3/8d828301-b1f8-4d87-9337-4c53cb6b4f90.png align="center")

### What affects inference performance?

- Model size.
- Input length.
- Output length.
- Hardware and available memory.
- Model configuration.
- Runtime implementation.
- Concurrent requests.

### Two useful performance metrics

**TPS (Tokens Per Second):** Measures how quickly a model generates output tokens.

**TTFT (Time to First Token):** Measures the delay before the first generated token becomes available.

These metrics are useful when evaluating AI application performance.

When we send a prompt to an LLM and receive an answer, the model is performing inference.

## 12\. What Is Hallucination in Generative AI?

Hallucination occurs when an AI model generates information that sounds correct but is incorrect, unsupported or fabricated.

For example, a model may confidently provide an answer to a question even when it does not have reliable information.

### Why do hallucinations happen?

Possible reasons include:

- Missing or insufficient context.
- Ambiguous prompts.
- Incomplete or unreliable source information.
- Model limitations.
- Incorrect interpretation of retrieved content.

### How can we reduce hallucinations?

1. Provide reliable context.
2. Use RAG with trusted documents.
3. Give clear instructions.
4. Validate structured outputs.
5. Check important facts against authoritative sources.
6. Ask the model to state when information is unavailable.
7. Apply business validation before executing important operations.

**Important:** RAG can help ground responses in supplied information, but it does not guarantee that hallucinations will never happen.

For enterprise applications, AI-generated responses should be validated before they are used for important business decisions.

## 13\. What Is RAG (Retrieval-Augmented Generation)?

RAG stands for Retrieval-Augmented Generation.

It is a technique that combines information retrieval with Generative AI.

Instead of relying only on the model's previously learned knowledge, an application retrieves relevant information from an external knowledge source and provides it as context to the model.

### Why do we need RAG?

Imagine an organization has thousands of internal documents:

- HR policies.
- Employee handbooks.
- Technical documentation.
- Deployment procedures.
- Product documentation.

A normal LLM may not know the latest internal company policies.

RAG helps an application retrieve relevant information from these documents before generating an answer.

### Example: Enterprise Knowledge Assistant

Imagine an organization has thousands of internal documents.

An employee asks:

"What is our company's leave policy?"

A typical RAG flow looks like this:

![](https://cdn.hashnode.com/uploads/covers/688293ee74301582de5306c3/f2710e1a-d835-4f57-a8f2-f984973a5934.png align="center")

A RAG-based application can:

1. Convert the employee's question into an embedding.
2. Search the document database.
3. Retrieve relevant policy sections.
4. Build a prompt using the retrieved content.
5. Send the prompt to the LLM.
6. Generate an answer based on the supplied context.

### RAG architecture: Two important workflows

**A. Document ingestion workflow**

This happens before a user asks a question.

1. Collect documents.
2. Extract text.
3. Split documents into smaller chunks.
4. Generate embeddings for each chunk.
5. Store embeddings and associated metadata in a vector database.

**B. Question retrieval workflow**

This happens when a user asks a question.

1. Receive the question.
2. Generate a query embedding.
3. Search for relevant document chunks.
4. Retrieve the matching content.
5. Add the retrieved content to the prompt.
6. Send the prompt to the LLM.
7. Return the generated answer.

### Where is RAG useful?

- Enterprise knowledge assistants.
- Internal documentation search.
- Customer support systems.
- Policy and compliance assistants.
- Technical documentation assistants.

### RAG vs Fine-Tuning

| RAG | Fine-Tuning |
| --- | --- |
| Retrieves external information at request time | Further trains a model on additional examples |
| Does not change model weights | Changes model weights |
| Useful for frequently changing knowledge | Useful for adapting model behavior |
| Requires a retrieval system | Requires a training workflow |

**For our project:** We'll implement RAG using Spring AI and PostgreSQL with pgvector.

## 14\. What Is Tool Calling?

Tool calling allows an AI model to request that an application execute a predefined function or tool.

This enables an AI-powered application to interact with external systems and business services.

### Example: Order Management System

A user asks:

"What is the status of order 12345?"

The AI model may determine that it needs an order lookup function.

The workflow looks like this:

1. User sends a question.
2. Model determines that an order lookup is required.
3. Model requests the predefined order lookup tool.
4. Application executes the function.
5. Tool returns the order information.
6. Model generates the final response.

A simplified flow:

![](https://cdn.hashnode.com/uploads/covers/688293ee74301582de5306c3/04e19bdf-9baf-49f4-a98d-dc523f328c9d.png align="center")

### Important: Does the LLM directly execute backend code?

No. The model requests a tool call, but the application controls the available tools and executes them.

For example, our Spring Boot application may expose a controlled order lookup function:

```java
public Order getOrderStatus(String orderId) {
    return orderRepository.findById(orderId)
            .orElseThrow(() ->
                    new IllegalArgumentException("Order not found"));
}
```

The application must validate the request, enforce authorization and control which operations can be executed.

### Where is tool calling useful?

- Order status lookup.
- Booking systems.
- Payment status checks.
- Customer support.
- Internal enterprise APIs.
- Database-backed business operations.

Tool calling connects an AI model to controlled application capabilities.

## 15\. What Is an AI Agent?

An AI agent is a system that uses an AI model to work towards a goal, often by selecting tools and performing multiple steps.

Unlike a simple prompt-and-response interaction, an agent may decide what action to take next based on intermediate results.

### Example: Order Support Agent

A customer asks:

"Where is my order, and when will it be delivered?"

An order-support agent might:

1. Understand the customer's request.
2. Identify the order lookup tool.
3. Retrieve the order status.
4. Retrieve delivery information.
5. Decide whether another action is needed.
6. Prepare a response.

### Chatbot vs Tool Calling vs AI Agent

| Concept | Purpose |
| --- | --- |
| Chatbot | Responds to user messages |
| Tool Calling | Allows a model to request application functions |
| AI Agent | Uses a model and available tools to work towards a goal through multiple steps |

Tool calling is often one of the building blocks used to create agents.

**Enterprise consideration:** Agents need controlled permissions, execution limits, monitoring and validation. They should not be given unrestricted access to business systems.

## 16\. What Is Ollama?

Ollama is a tool that allows developers to run supported AI models locally.

Instead of always depending on hosted AI services, developers can download and run models on their own machines.

### Why use Ollama?

- Experiment with local AI models.
- Learn LLM integration without requiring a hosted model API key.
- Test different models.
- Develop AI applications locally.
- Reduce dependence on external services during development.

### Our project technology choices

| Technology | Responsibility |
| --- | --- |
| Ollama | Local model runtime |
| Qwen 2.5 3B | Language model |
| Spring Boot | Backend framework |
| Spring AI | AI integration layer |
| PostgreSQL + pgvector | Data storage and vector search |

### Ollama default local API endpoint

```text
http://localhost:11434
```

For example, after installing Ollama and downloading a supported model, you can run:

```bash
ollama pull qwen2.5:3b
```

Then execute:

```bash
ollama run qwen2.5:3b
```

You can interact with the model directly from your terminal.

Ollama also exposes an HTTP API that applications can use to communicate with the running model.

**Important:** Local model performance depends on available CPU, GPU and memory. A 3B model is useful for experimentation, but its response quality and capabilities may differ from larger hosted models.

## 17\. What Is Spring AI?

Spring AI is a framework that helps Java developers integrate AI capabilities into Spring applications.

It provides abstractions and integrations for working with:

- Chat models.
- Prompts.
- Embeddings.
- Vector stores.
- RAG.
- Tool calling.

For Java developers, this means we can use familiar Spring Boot development patterns while adding AI capabilities.

### Why use Spring AI?

Without a framework, we may need to manage provider-specific APIs, request formats, response parsing and integration code ourselves.

Spring AI provides a consistent programming model for supported AI integrations.

This can make it easier to develop applications and switch between supported model providers.

For example, Spring AI provides `ChatClient` for interacting with chat models.

### A simple ChatClient example

```java
@Service
public class ChatService {

    private final ChatClient chatClient;

    public ChatService(ChatClient.Builder builder) {
        this.chatClient = builder.build();
    }

    public String generateResponse(String message) {

        return chatClient
                .prompt()
                .user(message)
                .call()
                .content();
    }
}
```

### What does ChatClient do?

The ChatClient API provides a fluent interface for interacting with chat models.

The application sends the prompt to the configured model and receives its response.

We'll build this integration step by step in a dedicated hands-on article.

## 18\. How Do All These Concepts Fit Together?

Now let's connect the concepts to a real enterprise use case.

Imagine we're building an **Enterprise GenAI Knowledge Assistant**.

An employee asks:

"Explain our production deployment process."

Our application needs to:

1. Receive the question through a REST API.
2. Convert the question into an embedding.
3. Search the internal knowledge base.
4. Retrieve relevant document content.
5. Build a prompt with the retrieved context.
6. Send the prompt to an LLM.
7. Generate a response.
8. Return the answer through the REST API.

### Proposed architecture

![](https://cdn.hashnode.com/uploads/covers/688293ee74301582de5306c3/843a21eb-1b1d-4257-9626-667cfaf16729.png align="center")

This is a simplified logical view. In an actual implementation, document ingestion, retrieval, embedding generation and chat generation are separate steps with their own components.

### Responsibility of each component

| Component | Responsibility |
| --- | --- |
| Spring Boot | Exposes REST APIs and manages application logic |
| Spring AI | Integrates AI capabilities |
| Embedding Model | Converts text into numerical vectors |
| PostgreSQL + pgvector | Stores and searches document embeddings |
| Ollama | Runs the local model |
| Qwen 2.5 | Generates natural-language responses |

**Important:** This is a simplified logical architecture. In a real implementation, document ingestion, embedding generation, retrieval and response generation are separate workflows with their own components.

### Why is this architecture useful?

It combines familiar Java backend technologies with AI capabilities.

We can use Spring Security for authentication, PostgreSQL for persistence, REST APIs for integration and Spring AI for model interaction.

This is the foundation for building an enterprise AI application.

## 19\. Learning Roadmap: From GenAI Fundamentals to Enterprise Application

This is the recommended sequence for Java backend developers who want to build practical AI applications and prepare for senior-level interviews.

| # | Topic | What you'll learn | Practical outcome |
| --: | --- | --- | --- |
| 1 | GenAI Fundamentals | AI, ML, DL, LLMs, prompts, embeddings, RAG | Understand the ecosystem |
| 2 | Tokens and Tokenization | Token IDs, input/output tokens, TPS, TTFT | Measure model usage |
| 3 | LLM Architecture | Transformers, attention, inference, context window | Understand model internals |
| 4 | Spring AI and Ollama | ChatClient, model configuration, REST integration | First Java AI API |
| 5 | Prompt Engineering | System prompts, user prompts, temperature, structured output | Reliable responses |
| 6 | Embeddings and Vector Databases | Semantic search, vector similarity, pgvector | Search documents by meaning |
| 7 | RAG with Spring AI | Chunking, ingestion, retrieval, prompt augmentation | Knowledge assistant |
| 8 | Tool Calling and AI Agents | Functions, tools, execution, agent workflows | Connect AI to backend services |
| 9 | Enterprise GenAI Project | Security, memory, validation, observability, testing | Complete backend application |
| 10 | Docker and AWS Deployment | Docker, ECR, ECS Fargate, RDS, S3, CI/CD | Deploy to cloud |

### What should we build?

Our end-to-end project will be:

**Enterprise GenAI Knowledge Assistant**

Planned technologies:

- Java 21.
- Spring Boot.
- Spring AI.
- Ollama and Qwen 2.5 3B for local development.
- PostgreSQL and pgvector.
- Docker and Docker Compose.
- AWS ECS Fargate, ECR, RDS and S3 for deployment.
- GitHub Actions for CI/CD.

We'll start locally and design the application so that switching from a local model to a hosted provider later requires minimal application changes.

### What will the project demonstrate?

By the end, we'll have practical experience with:

- Integrating an LLM into a Java application.
- Generating and storing embeddings.
- Implementing semantic search.
- Building a RAG pipeline.
- Connecting AI models to backend tools.
- Securing AI-powered APIs.
- Monitoring and deploying an enterprise AI application.

## 20\. Important Generative AI Interview Questions and Answers

These are high-priority questions for Java Backend Lead, Staff Engineer and AI application engineering interviews. They cover fundamentals, application architecture and production concerns.

### A. Generative AI and LLM fundamentals

**Q1. What is Generative AI?**

Generative AI creates new content such as text, images, audio and code based on user input and learned patterns.

**Q2. What is an LLM?**

A Large Language Model is a model trained on large amounts of data to understand and generate language.

**Q3. What is the difference between AI, ML and Deep Learning?**

AI is the broad field, ML is a subset of AI that learns patterns from data, and Deep Learning is a subset of ML that uses multi-layer neural networks.

**Q4. What is a foundation model?**

A model trained on broad datasets that can be adapted for multiple downstream tasks.

**Q5. How does an LLM generate a response?**

It processes tokenized input and repeatedly predicts the next token until it reaches a stopping condition.

**Q6. What is inference?**

Inference is the process of using a trained model to generate predictions or responses for new input.

### B. Tokens, prompts and model performance

**Q7. What is a token?**

A token is a unit of text processed by an LLM. It may be a word, part of a word or punctuation.

**Q8. What is tokenization?**

Tokenization converts text into smaller units called tokens.

**Q9. What is a context window?**

The maximum amount of tokenized information a model can handle in one context, including input and available output capacity.

**Q10. What is the difference between input and output tokens?**

Input tokens are provided to the model; output tokens are generated by the model.

**Q11. What is temperature?**

Temperature controls the randomness of token selection. Lower values generally produce more predictable responses.

**Q12. What is Top-K and Top-P sampling?**

Top-K limits candidate next tokens to the K most likely choices. Top-P selects from the smallest candidate set whose cumulative probability reaches a configured threshold.

**Q13. What is TPS?**

Tokens per second measures output generation speed: generated output tokens divided by generation time.

**Q14. What is TTFT?**

Time to First Token measures the delay before the first generated token becomes available.

### C. Embeddings, RAG and vector databases

**Q15. What are embeddings?**

Embeddings are numerical vectors representing data such as text, allowing semantic similarity comparisons.

**Q16. What is the difference between keyword search and semantic search?**

Keyword search matches terms, while semantic search attempts to retrieve content based on meaning.

**Q17. What is RAG?**

Retrieval-Augmented Generation retrieves relevant external information and provides it as context to an LLM before generating an answer.

**Q18. Why do we need a vector database?**

It stores and searches vector embeddings efficiently, helping retrieve semantically similar content.

**Q19. What is chunking in RAG?**

Chunking splits large documents into smaller pieces so that relevant content can be embedded, indexed and retrieved.

**Q20. What are the important factors when choosing chunk size?**

Document structure, information density, embedding model limits, retrieval quality, context window and overlap requirements.

**Q21. What is the difference between an embedding model and a chat model?**

An embedding model converts data into vectors; a chat model generates conversational responses.

**Q22. Does RAG eliminate hallucinations?**

No. RAG can ground responses in retrieved information, but retrieval errors or model interpretation can still produce incorrect answers.

### D. Spring AI, tools and agents

**Q23. What is Spring AI?**

Spring AI provides Spring-friendly abstractions and integrations for building AI-powered Java applications.

**Q24. What is ChatClient in Spring AI?**

ChatClient is a fluent API for sending prompts to chat models and processing their responses.

**Q25. What is the difference between Ollama and Spring AI?**

Ollama runs supported models locally and exposes an API. Spring AI integrates model capabilities into Spring applications.

**Q26. What is tool calling?**

Tool calling allows a model to request that the application execute predefined functions or operations.

**Q27. What is an AI agent?**

An AI agent uses a model to decide how to achieve a goal, potentially by selecting tools and performing multiple steps.

**Q28. Can an LLM directly access our database?**

Not by default. Our application must expose controlled tools or services, enforce authorization and execute the database operations.

### E. Enterprise architecture and production readiness

**Q29. How would you design an enterprise knowledge assistant?**

Use a Spring Boot API, Spring AI, an embedding model, document ingestion, a vector store, retrieval, prompt augmentation and a chat model. Add security, monitoring and validation around the workflow.

**Q30. How would you reduce latency in an AI application?**

Optimize prompt size, retrieve fewer but more relevant chunks, select an appropriate model, use streaming where useful, manage model loading and measure each stage independently.

**Q31. How would you reduce LLM costs?**

Use smaller suitable models, limit unnecessary context, optimize retrieval, control output length, cache appropriate results and monitor token usage.

**Q32. How would you protect sensitive enterprise data?**

Apply authentication and authorization, enforce access control during retrieval, protect data in transit and at rest, manage secrets securely and avoid sending unauthorized information to external providers.

**Q33. How do you evaluate RAG quality?**

Measure retrieval relevance and answer quality separately. Evaluate whether retrieved chunks contain the required evidence and whether the answer is accurate, relevant and grounded.

**Q34. What is the difference between fine-tuning and RAG?**

Fine-tuning changes model behavior through additional training. RAG provides external information at request time without changing the model's weights.

**Q35. How would you monitor a production GenAI application?**

Monitor latency, errors, token usage, model/provider availability, retrieval quality, throughput and cost. Use traces and structured logs while protecting sensitive prompt data.

## 21\. Practical Exercises for Java Developers

Before moving to the next article, try these exercises.

### Beginner

1. Explain the difference between traditional programming and Generative AI using a real backend example.
2. Write a system prompt for a Java interview assistant.
3. Identify input and output tokens in a sample AI request.
4. Explain why two sentences with different words can have similar embeddings.

### Intermediate

5. Draw a simple RAG architecture for an employee knowledge assistant.
6. Explain how tool calling can connect an LLM to an order-management API.
7. Explain the roles of Spring Boot, Spring AI, Ollama and Qwen in our project.
8. Compare keyword search with semantic search.

### Advanced

9. Design a RAG system for internal company documents.
10. Explain how you would secure document retrieval for different employee roles.
11. Identify possible latency bottlenecks in an enterprise GenAI application.
12. Explain how you would monitor and evaluate the quality of AI-generated responses.

## 22\. Important Takeaways

Let's summarize the important concepts covered in this article.

- **Artificial Intelligence:** The broader field of building intelligent systems.
- **Machine Learning:** Systems learn patterns from data.
- **Deep Learning:** Uses multi-layer neural networks.
- **Generative AI:** Generates new content based on learned patterns.
- **LLMs:** Generate language by predicting tokens.
- **Prompts:** Provide instructions and context to models.
- **Tokens:** Influence model usage, context size and performance.
- **Embeddings:** Represent semantic information as numerical vectors.
- **Transformers:** Use attention mechanisms to process relationships between tokens.
- **Inference:** Uses a trained model to generate predictions or responses.
- **RAG:** Retrieves external information to help ground model responses.
- **Tool Calling:** Connects AI models to controlled application functions.
- **AI Agents:** Use models and tools to work towards goals.
- **Ollama:** Provides a local model runtime.
- **Spring AI:** Helps Java developers integrate AI capabilities into Spring applications.

Understanding these concepts gives us a strong foundation for building scalable and reliable enterprise AI applications.

## 23\. What's Next?

In the next article, we'll go deeper into one of the most important LLM concepts:

**Understanding Tokens and Tokenization in Generative AI: A Practical Guide Using Ollama and Qwen 2.5.**

We'll explore:

- How text becomes tokens and token IDs.
- Input tokens versus output tokens.
- How to measure token usage using Ollama.
- Tokens per second (TPS).
- Time to First Token (TTFT).
- Context window limits.
- A practical PowerShell experiment using Qwen 2.5 3B.

Then we'll move into LLM architecture and our first Spring AI integration.

**Technologies covered in this series:** Java 21, Spring Boot, Spring AI, Ollama, Qwen 2.5, PostgreSQL and pgvector.

Happy Learning! 🚀

---

### About the Author

**Praveen Gupta** is a Java Backend Engineer with 12+ years of experience in Java, Spring Boot, microservices, cloud technologies and enterprise application development.

Through **CodeWithPraveen**, he shares practical tutorials, architecture guides and hands-on learning resources for Java developers.

Connect with me on [LinkedIn](https://www.linkedin.com/in/praveen-gupta-520b2543/).

### References and Further Reading

For official documentation and deeper technical understanding:

1. [Spring AI Documentation](https://docs.spring.io/spring-ai/reference/)
2. [Spring Boot Documentation](https://docs.spring.io/spring-boot/index.html)
3. [Ollama Documentation](https://docs.ollama.com/)
4. [PostgreSQL Documentation](https://www.postgresql.org/docs/)
5. [pgvector – Vector Similarity Search for PostgreSQL](https://github.com/pgvector/pgvector)
6. [OpenAI Documentation – Embeddings](https://platform.openai.com/docs/guides/embeddings)

### 💬Feedback?

Found this article useful?

Leave a comment, share your feedback or connect with me on LinkedIn.

If you're learning Generative AI with Java, follow **CodeWithPraveen** for the upcoming hands-on Spring AI series.

#GenerativeAI #Java #SpringBoot #SpringAI #LLM #RAG #Ollama #ArtificialIntelligence #MachineLearning #DeepLearning #PromptEngineering #Embeddings #VectorDatabase #Qwen #JavaDeveloper
