Understanding LLM & RAG

AI & HCI
LLM과 RAG 완벽 이해 [정확도 향상의 핵심 전략]
Posted on Sept. 2, 2025, 5:32 a.m. by SANGJIN
random_image

Understanding LLM & RAG [Reliable AI]

Understanding LLM & RAG [Reliable AI]

LLM과 RAG 완벽 이해 [정확도 향상의 핵심 전략]

Take-home message: RAG strategies are essential to enhance the accuracy and trustworthiness of LLMs.

1. What is an LLM?

A Large Language Model (LLM) is a deep neural network trained on massive text corpora, capable of understanding, reasoning, and generating human-like language. These models, such as GPT-4, Claude, and LLaMA 3, leverage billions of parameters to build representations of language and knowledge.

LLMs are based on the Transformer architecture, which includes:

  • Self-Attention: This mechanism allows each token to evaluate the relevance of other tokens in the input sequence, enabling nuanced contextual understanding.
  • Positional Encoding: Since Transformers lack a sense of order, positional encodings are added to give tokens sequence information.
  • Decoder Blocks: In GPT-style models, only the decoder part of the Transformer is used for autoregressive generation.

2. What is a Token and Why is it Important?

A token is the smallest unit of text that an LLM processes. It can be a full word, a sub-word, a space, or punctuation. The model reads and generates text as sequences of tokens, not words or characters.

Example:
Input text: "I love AI."
Tokens: ['I', ' love', ' AI', '.']
  
  • Context Window: Each LLM has a fixed token limit per request. GPT-4 supports 8K to 32K tokens depending on the variant.
  • Billing: Most APIs charge based on token usage, making token optimization critical for cost management.
  • Performance: Overflowing tokens beyond the context window can lead to information being ignored or hallucinated.

3. How are LLMs Built?

  1. Pretraining: The model is trained on massive unlabeled data to predict the next token in a sequence. This allows it to learn grammar, semantics, facts, and even reasoning patterns.
  2. Fine-tuning: After pretraining, the model can be adjusted with domain-specific data to specialize in tasks such as medical diagnosis or legal reasoning.
  3. RLHF (Reinforcement Learning from Human Feedback): Human annotators rank different outputs, and the model is refined using techniques like Proximal Policy Optimization (PPO) to align responses with human preferences.

4. Why is RAG Needed?

LLMs are powerful, but they have notable limitations:

  • They cannot access real-time or post-training knowledge.
  • They often hallucinate facts when asked about information not well represented in training data.
  • They struggle with domain-specific tasks without extensive fine-tuning.

Retrieval-Augmented Generation (RAG) enhances LLMs by allowing them to retrieve external documents or knowledge and integrate it into their response generation process in real time.

5. How RAG Works

RAG systems combine two powerful components: semantic search and generative modeling. Here’s a detailed breakdown of how RAG operates:

  1. Retrieval: When a user submits a query, it is embedded using a sentence transformer or embedding model (e.g., OpenAI, BGE, Cohere). This embedded vector is used to search a vector database such as FAISS or Pinecone, which returns the most semantically relevant documents.
  2. Augmentation: The retrieved documents are injected into the prompt alongside the original question. This gives the LLM direct access to domain-specific or up-to-date information.
  3. Generation: The LLM uses both the user’s query and the retrieved knowledge to generate a grounded and accurate response, reducing the risk of hallucinations.

RAG doesn’t require retraining the base model. Instead, it acts as a knowledge layer around the model, making it more adaptable and cost-effective.

Advanced practices include:

  • Document chunking for better granularity
  • Hybrid retrieval (keyword + semantic)
  • Context window optimization using top-k filtering and scoring

6. Use Cases and Tools for RAG

RAG is widely used in production systems today, and open-source tools have made implementation increasingly accessible:

  • LangChain: Orchestrates multi-step LLM pipelines including retrieval, prompt templating, and tool use.
  • LlamaIndex: Focused on building vector indexes from custom data sources for powerful RAG queries.
  • Haystack: Provides an end-to-end framework for building question-answering systems using search + generation.

Key applications include:

  • Enterprise knowledge base assistants (e.g., company HR or IT policies)
  • Medical or legal support bots grounded in verified documents
  • Code documentation assistants that understand internal repositories
  • Multilingual customer support bots with localized content

7. Is Uploading a File to ChatGPT the Same as RAG?

Many users wonder whether uploading a file to ChatGPT and asking it to “refer to this” is equivalent to RAG. The short answer is: not exactly — but it’s similar in principle.

When you upload a file in ChatGPT Pro (e.g., PDF or CSV), OpenAI's system extracts the content, splits it into chunks, embeds it, and matches your query semantically to relevant chunks — injecting them into the prompt. This process is functionally very similar to a basic RAG pipeline.

However, from an architectural perspective, it’s different:

Feature ChatGPT File Upload Custom RAG System
Search Scope Only uploaded file Internal DBs, vector indexes, entire corpora
Control Automated, opaque Fully customizable
Extensibility Not possible Custom scoring, reranking, hybrid retrieval
Tools Built-in (OpenAI backend) LangChain, LlamaIndex, FAISS, Pinecone, etc.

In short, ChatGPT’s file reference system is a simplified, automated version of RAG — great for casual use, but not suitable for scalable, domain-specific, or real-time systems.


1. LLM이란 무엇인가?

LLM(Large Language Model)은 대규모 텍스트 데이터를 기반으로 학습한 딥러닝 언어 모델로, 인간처럼 언어를 이해하고 생성할 수 있는 능력을 가진다. GPT, Claude, LLaMA와 같은 모델은 수십억 개 이상의 파라미터를 통해 문장 구조, 의미, 지식 등을 내재화한다.

이러한 모델은 Transformer 구조를 기반으로 하며, 다음과 같은 핵심 기술을 포함한다:

  • Self-Attention: 각 토큰이 입력 문장 내 다른 토큰과의 관계를 동적으로 계산하여 문맥을 파악한다.
  • Positional Encoding: 토큰의 순서를 모델에 전달하여 문장의 구조를 인식하게 한다.
  • 디코더 블록: GPT 계열은 Transformer의 디코더만 사용하여 다음 토큰을 예측하는 구조를 사용한다.

2. 토큰이란 무엇이며 왜 중요한가?

토큰은 LLM이 텍스트를 처리할 때 사용하는 최소 단위이며, 단어 전체일 수도 있고, 단어의 일부분, 공백, 구두점 등이 될 수도 있다. 모델은 단어 단위가 아닌 토큰 시퀀스를 기반으로 텍스트를 읽고 생성한다.

예시:
입력 텍스트: "I love AI."
토큰 결과: ['I', ' love', ' AI', '.']
  
  • 문맥 길이 제한: GPT-4는 8K~32K 토큰 범위의 입력을 허용하며, 이를 초과하면 일부 정보가 무시된다.
  • 비용 계산 단위: 대부분의 API는 사용된 토큰 수에 따라 과금되므로 관리가 필요하다.
  • 정확도 영향: 토큰이 너무 많아지면 컨텍스트가 잘리거나 환각이 발생할 수 있다.

3. LLM은 어떻게 만들어지는가?

  1. 사전 학습: 대규모의 웹 텍스트, 책, 코드 등으로 구성된 데이터셋을 사용하여 다음 토큰을 예측하는 방식으로 학습한다. 이를 통해 언어의 통계적 패턴, 개념, 사실 등을 모델이 내재화한다.
  2. 미세 조정: 특정 분야(예: 의료, 법률) 또는 태스크(요약, 번역)에 특화되도록 별도의 데이터로 추가 학습을 진행한다.
  3. RLHF: 인간의 피드백을 수집하고 이를 보상 함수로 활용하여 모델 응답 품질을 향상시키는 방식이다. PPO 알고리즘이 자주 사용된다.

4. 왜 RAG가 필요한가?

LLM은 매우 강력하지만 다음과 같은 한계를 가진다:

  • 학습 시점 이후의 정보를 알 수 없다.
  • 정확하지 않은 정보를 그럴듯하게 만들어내는 환각 문제가 존재한다.
  • 특정 도메인 지식이 부족하다.

이러한 한계를 극복하기 위해 RAG(Retrieval-Augmented Generation)가 등장하였다. RAG는 외부 검색 시스템을 활용하여 모델이 최신이거나 도메인 특화된 정보를 기반으로 응답을 생성하도록 돕는다.

5. RAG는 어떻게 작동하는가?

RAG는 검색 기반 시스템과 언어 모델을 결합하여 정보를 검색하고, 이를 활용해 보다 정확한 응답을 생성하는 방식이다. 다음은 작동 단계이다:

  1. 검색(Retrieval): 사용자의 질문을 벡터로 임베딩한 후, FAISS나 Pinecone과 같은 벡터 DB에서 의미적으로 가장 가까운 문서를 검색한다.
  2. 증강(Augmentation): 검색된 문서를 LLM의 입력 프롬프트에 삽입하여, 해당 정보가 응답 생성에 반영되도록 한다.
  3. 생성(Generation): LLM은 질문과 함께 제공된 문서를 기반으로 정답을 생성하며, 이로 인해 환각 가능성이 줄고 정확도는 높아진다.

이 구조는 모델 자체를 재학습할 필요 없이 실시간으로 외부 정보를 반영할 수 있게 해주며, 구축 및 운영 비용도 낮출 수 있다.

  • 문서 청킹(Chunking)을 통해 문서 단위를 세분화할 수 있다.
  • 검색 결과를 재정렬(Re-ranking)하거나 스코어링하여 품질을 높일 수 있다.
  • 여러 개의 쿼리를 생성하여 다양한 각도에서 문서를 찾는 멀티 쿼리 전략도 효과적이다.

6. RAG 적용 사례 및 프레임워크

RAG는 현재 많은 실무 시스템에서 사용되고 있으며, 다음과 같은 오픈소스 프레임워크가 이를 지원한다:

  • LangChain: 검색, 프롬프트 생성, 도구 활용 등을 조합한 체인 파이프라인 구축에 적합하다.
  • LlamaIndex: 사내 문서, PDF, 웹 페이지 등 다양한 소스로부터 벡터 인덱스를 생성하여 효율적인 검색 기반 응답 시스템을 구현할 수 있다.
  • Haystack: 문서 검색과 LLM 생성 기능을 결합한 QA 시스템 구축용 프레임워크다.

대표적인 활용 사례는 다음과 같다:

  • 사내 정책, IT 가이드, HR 문서 기반의 챗봇
  • 의료 및 법률 문서를 활용한 정밀 질의응답 시스템
  • 코드 검색과 문서화를 지원하는 개발자 도우미
  • 다국어 지원이 가능한 고객센터 챗봇

7. ChatGPT에 파일 업로드하는 기능은 RAG와 같은가?

많은 사용자들이 "ChatGPT에 파일을 업로드하고 '이걸 참고해줘'라고 하는 것이 RAG와 같은 개념인가?"라는 질문을 한다. 결론부터 말하면: 완전히 같지는 않지만, 유사한 개념을 기반으로 한다.

ChatGPT (Pro 기능)에서 PDF, CSV 등의 파일을 업로드하면 OpenAI 시스템은 해당 문서를 텍스트로 변환하고, chunk 단위로 분할한 뒤 벡터 임베딩하여 사용자의 질문과 의미적으로 유사한 부분을 찾아 프롬프트에 삽입한다. 이 프로세스는 기본적인 RAG 아키텍처와 거의 유사하다.

그러나 기술적인 구조와 확장성에서는 명확한 차이가 있다:

항목 ChatGPT 파일 업로드 커스텀 RAG 시스템
검색 범위 업로드된 파일 내에서만 사내 DB, 위키, 벡터 인덱스 전체
제어 가능성 자동화됨, 사용자 제어 불가 chunk 전략, 검색 알고리즘 등 완전 제어 가능
확장성 한 파일, 일회성 응답 다중 데이터 소스, API 연동, 실시간 대응 가능
도구 OpenAI 내부 처리 LangChain, LlamaIndex, FAISS, Pinecone 등

요약하자면, ChatGPT의 파일 참고 기능은 사용자가 직접 구현하는 RAG의 축소판 또는 자동화된 형태라고 볼 수 있다. 빠른 참고용으로는 매우 유용하지만, 확장성과 도메인 특화 정확도를 요하는 시스템에는 부족하다.

LLM AI ChatGPT

Leave a Comment: