Elastic
Jina AI
모델
API
keyboard_arrow_down
Reader
어떤 URL이든 Markdown으로 변환하여 LLM 그라운딩을 개선하세요.
Embeddings
멀티모달 및 다국어 임베딩.
Reranker
검색 관련성을 극대화하는 리랭커.
Elastic Inference Service
Jina 모델을 Elasticsearch에서 네이티브 방식으로 실행하세요.
MCP
terminal
CLI
article
llms.txt
smart_toy
에이전트
data_object
스키마
menu_book
문서
로그인
login
RAG의 맥락
RAG 시스템의 구조
필수 요소 설치
Hugging Face Inference API를 통해 Mistral-Instruct에 연결하기
Qdrant와 Jina Embeddings를 사용한 정보 검색
Jina AI와 Qdrant
연락하기
기술 블로그
3월 04, 2024

Jina Embeddings와 Qdrant를 사용한 RAG 시스템 구축

Jina Embeddings v2, Qdrant 벡터 데이터베이스, LlamaIndex, 그리고 Mistral LLM을 사용하여 RAG 시스템 만들기
Promotional graphic with "EMBEDDINGS 2" and Drant logo separated by a red cross, symbolizing a partnership.
Scott Martens • 13 분 소요

데이터 검색 강화 생성(Retrieval-augmented generation)은 원래 대규모 언어 모델(LLM)의 확장으로 처음 고안되었지만, 이제는 AI 모델의 역할을 완전히 재구상하는 대안적 패러다임으로 빠르게 발전하고 있는 기술입니다.

우리는 LlamaIndex 프레임워크, 오픈소스 Mistral LLM, Jina Embeddings v2, 그리고 Qdrant의 AI 지원 벡터 데이터베이스를 사용하여 기본적인 RAG 엔진을 만드는 방법을 보여드리겠습니다.

tagRAG의 맥락

RAG 시스템에서 AI 모델의 역할은 여전히 중심적이지만 훨씬 더 제한적입니다. 학습 데이터에서 얻은 내부 지식을 바탕으로 프롬프트에 답하는 대신, 프롬프트에 관련 정보가 제시됩니다. 그러면 모델의 역할은 정보를 이해하고 종합하여 출력하는 것입니다.

이는 AI 모델의 강점을 살리고 약점을 최소화합니다.

예를 들어, Mistral-Instruct 모델에 다음과 같은 프롬프트를 제시할 수 있습니다:

Answer the query. Please be brief, concise, and complete.
Query: Why is Taylor Swift planning to attend the Superbowl?
Answer:

이때 모델은 다음과 같이 응답했습니다:

I don't have real-time information. However, as of my last update, 
Taylor Swift is not officially confirmed to attend or perform at 
the Superbowl. If there are any updates, I recommend checking the 
latest news sources.

대규모 언어 모델은 업데이트와 재학습이 비용이 많이 들기 때문에, 내부 정보가 완전히 최신 상태일 수 없습니다.

또한, 대규모 언어 모델은 "환각"을 일으키는 것으로 잘 알려져 있습니다. 즉, 부분적으로 또는 전체적으로 잘못될 수 있는 그럴듯한 답변을 만들어내며 이는 검증이 필요합니다.

Answer the query. Please be brief, concise, and complete.
Query: What was Weird Al Yankovic's first Taylor Swift parody?
Answer:

Weird Al Yankovic's first Taylor Swift parody was "TMZ," a spoof 
of Swift's song "Blank Space." The parody was released in 2014 
as part of Yankovic's album "Mandatory Fun." The song humorously 
addresses the obsession with celebrity gossip and scandals, as 
reported by the tabloid news website TMZ.

Weird Al Yankovic의 TMZ는 2011년 Alpocalypse 앨범에서 발매되었으며 Swift의 You Belong with Me의 패러디입니다.

신경망의 특성상 환각을 완전히 방지하는 것은 어렵거나 불가능하며, 이는 AI 모델을 정보 소스로 사용하려는 계획을 크게 약화시킵니다.

OpenAI의 CEO인 Sam Altman의 말에 따르면:

"사람들이 이러한 모델들[LLM]을 데이터베이스로 생각하는 것은 큰 실수라고 봅니다. [...] 어느 정도는 작동할 것입니다. 하지만 그것은 세상에서 가장 비싸고, 가장 느리며, 가장 부정확한 데이터베이스입니다."

RAG는 세상에 대한 AI 모델의 내부 지식에 대한 의존도를 최소화하고 자연어 이해와 유창한 언어 생성이라는 가장 큰 강점을 활용합니다.

Mistral-Instruct가 답할 수 없는 또 다른 질문의 예를 보겠습니다:

Answer the query. Please be brief, concise, and complete.

Query: What is the title of Taylor Swift's next album?
Answer:

As of the time I am providing this answer, Taylor Swift has 
not yet announced the title of her next album. She has released 
several re-recorded albums, but the title of her next original 
album remains unknown. I recommend checking her official social 
media channels or website for the latest updates.

이제 RAG 시스템은 최근 뉴스 기사의 데이터베이스를 가지고 있거나 Taylor Swift의 다음 앨범 제목과 관련된 텍스트를 인터넷에서 검색할 수 있습니다. 그런 다음 찾은 텍스트를 프롬프트에 삽입합니다.

이 AP 기사가 질문과 관련이 있다고 판단하고 다음과 같은 프롬프트를 구성했다고 가정해 봅시다:

Context information is below.
---------------------
February 6, 2024
LOS ANGELES (AP) — Forget her "Reputation." Taylor Swift has 
whole new album coming out.

Accepting the Grammy for best pop vocal album on Sunday night, 
Taylor said she'd been keeping a secret for two years.

"My brand-new album comes out April 19. It's called 'The Tortured 
Poets Department.' I'm going to go and post the cover right now 
backstage," she announced.

And so she did.

---------------------
Given the context information and not prior knowledge, answer the query. 
Please be brief, concise, and complete.
If the context information does not contain an answer to the query, 
respond with "No information".
Query: What is the title of Taylor Swift's next album?
Answer:

Mistral-Instruct는 다음과 같이 응답했습니다:

The title of Taylor Swift's next album is 'The Tortured Poets Department'.

이러한 종류의 프롬프팅은 환각이 발생할 가능성도 크게 줄입니다. 예를 들어:

Context information is below.
---------------------
Alpocalypse is the thirteenth studio album by American parody 
musician "Weird Al" Yankovic, released on June 21, 2011.

Track List

1. Perform This Way (Parody of "Born This Way" by Lady Gaga)
2. CNR
3. TMZ (Parody of "You Belong with Me" by Taylor Swift)
4. Skipper Dan
5. Polka Face (Polka medley including songs by artists such as 
   Lady Gaga, Justin Bieber, Britney Spears, Ke$ha, and others)
6. Craigslist
7. Party in the CIA (Parody of "Party in the U.S.A." by Miley 
   Cyrus)
8. Ringtone
9. Another Tattoo (Parody of "Nothin' on You" by B.o.B featuring 
   Bruno Mars)
10. If That Isn't Love
11. Whatever You Like (Parody of "Whatever You Like" by T.I.)
12. Stop Forwarding That Crap to Me

---------------------
Given the context information and not prior knowledge, answer the 
query. Please be brief, concise, and complete.
If the context information does not contain an answer to the query, 
respond with "No information".
Query: What was Weird Al Yankovic's first Taylor Swift parody, what 
year was it released, and what song was he parodying?
Answer:

Weird Al Yankovic's first Taylor Swift parody was "TMZ," and it was 
released in 2011. He was parodying "You Belong with Me" by Taylor 
Swift.

tagRAG 시스템의 구조

RAG 시스템은 최소한 두 가지 구성 요소가 있습니다:

  • 생성형 AI 모델
  • 정보 검색 시스템

이 글에서는 Mistral-Instruct를 생성형 AI 모델로 사용하고 Hugging Face Inference API를 통해 접근할 것입니다. 정보 검색 시스템으로는 Qdrant 벡터 데이터베이스와 Jina Embeddings를 함께 사용할 것입니다.

데이터 소스로는 2023년 5월 미국 대통령의 과학 기술 자문 기구인 국가과학기술위원회가 발표한 국가 인공지능 연구개발 전략 계획 2023 업데이트를 사용할 것입니다. 이 약 25,000단어의 문서는 미국의 AI 정책과 개발을 위한 정책 및 전략 계획 문서입니다.

이는 또한 전형적인 "tl;dr" 정부 정책 문서입니다. 대부분이 매우 지루하며, 이 분야에 특별한 이해관계나 관심이 없다면 아마 읽지 않을 것입니다. 하지만 여전히 그 내용이 무엇인지 알고 싶을 수 있습니다.

이 글에서는 텍스트와 그 내용에 대한 질문에 답할 수 있는 RAG 시스템을 만드는 단계를 안내할 것입니다.

tag필수 요소 설치

먼저 관련된 모든 Python 라이브러리가 설치되어 있는지 확인하세요. Python 환경에서 다음을 실행하세요:

pip install llama-index qdrant-client 
pip install pdfminer.six llama-index-vector-stores-qdrant
pip install llama-index-llms-openai llama-index-embeddings-jinaai 
pip install llama-index-llms-huggingface "huggingface_hub[inference]"

우리는 LlamaIndex를 사용하여 Mistral-Instruct 대규모 언어 모델을 중심으로 RAG 시스템을 구축하고, pdfminer.six를 사용하여 PDF 파일을 Qdrant 벡터 스토어로 처리할 것입니다.

tagHugging Face Inference API를 통해 Mistral-Instruct에 연결하기

먼저 LLM을 설정합니다. Hugging Face Inference API에 접근하려면 액세스 토큰이 필요합니다. Hugging Face 계정이 있다면 계정 설정 페이지에서 받을 수 있습니다.

계정이 없다면 먼저 계정을 만든 다음, 액세스 토큰을 생성하세요.

나중에 사용할 수 있도록 토큰을 변수에 저장하세요:

hf_inference_api_key = '<your HuggingFace Inference API token>'

다음으로 프롬프트 템플릿을 구성합니다:

from llama_index.core import PromptTemplate

qa_prompt_tmpl = (
    "Context information is below.\n"
    "---------------------\n"
    "{context_str}\\n"
    "---------------------\n"
    "Given the context information and not prior knowledge, "
    "answer the query. Please be brief, concise, and complete.\n"
    "If the context information does not contain an answer to the query, "
    "respond with \"No information\".\n"
    "Query: {query_str}\n"
    "Answer: "
)
qa_prompt = PromptTemplate(qa_prompt_tmpl)

이 템플릿은 LLM에게 질문에 답하기 위해 프롬프트에 제공된 컨텍스트 정보만을 사용하도록 지시합니다. 이 프롬프트는 Mistral-Instruct와의 작업에서 잘 작동했지만, 여러분의 사용 사례에 맞게 다른 문구를 실험해볼 수 있습니다.

from llama_index.llms.huggingface import HuggingFaceInferenceAPI

mixtral_llm = HuggingFaceInferenceAPI(
    model_name="mistralai/Mixtral-8x7B-Instruct-v0.1", 
    token=hf_inference_api_key
)

마지막으로 Mistral-Instruct에 대한 연결을 보유하는 LlamaIndex 프레임워크용 객체를 생성하고 초기화합니다. 아래 코드는 LlamaIndex를 사용한 RAG 시스템 구축에 관한 이전 게시물에서 가져온 것입니다.

이는 Mistral LLM에 대한 연결을 mistral_llm 변수에 저장합니다.

tagQdrant와 Jina Embeddings를 사용한 정보 검색

검색 시스템을 설정하려면 Jina Embeddings API 키가 필요합니다. Jina Embeddings 웹사이트에서 100만 토큰의 선불 예산으로 무료로 얻을 수 있습니다.

Embedding API
Start with 1M free tokens. Top-performing, 8192 context length bilingual embeddings for your search and RAG systems.

나중에 사용할 수 있도록 Jina Embeddings 키를 변수에 저장하세요:

jina_emb_api_key = "<your Jina Embeddings API key>"

그런 다음, LlamaIndex를 사용하여 Jina Embeddings 서버용 커넥터 객체를 생성하고, 영어 단일어 모델을 특별히 선택합니다:

from llama_index.embeddings.jinaai import JinaEmbedding

jina_embedding_model = JinaEmbedding(
    api_key=jina_emb_api_key,
    model="jina-embeddings-v2-base-en",
)

tag텍스트 데이터 로드

다음으로, 문서를 로드하고 단락으로 나눌 것입니다. 먼저 White House 웹사이트에서 PDF를 다운로드하여 pdf_data 변수에 저장합니다:

import urllib.request

uri = "https://www.whitehouse.gov/wp-content/uploads/2023/05/National-Artificial-Intelligence-Research-and-Development-Strategic-Plan-2023-Update.pdf"
pdf_data = urllib.request.urlopen(uri).read()

다음으로, PDF를 페이지별로 처리하여 텍스트를 추출한 다음 이중 줄바꿈을 기준으로 분할하여 단락으로 나눕니다. 이들은 text_paras 리스트에 저장됩니다:

import regex as re
from io import BytesIO, StringIO
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfdocument import PDFDocument
from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.pdfpage import PDFPage
from pdfminer.pdfparser import PDFParser

text_paras = []
parser = PDFParser(BytesIO(pdf_data))
doc = PDFDocument(parser)
rsrcmgr = PDFResourceManager()
for page in PDFPage.create_pages(doc):
    output_string = StringIO()
    device = TextConverter(rsrcmgr, output_string, laparams=LAParams())
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    interpreter.process_page(page)
    page_text = output_string.getvalue()
    text_paras.extend(re.split(r'\n\s*\n', page_text))

모든 것이 로드되었는지 확인합니다:

assert len(text_paras) == 615

다음으로, 이 짧은 텍스트 리스트를 LlamaIndex Document 객체로 변환할 것입니다:

from llama_index.core.readers import StringIterableReader

rag_docs = StringIterableReader().load_data(text_paras)

텍스트를 검사할 수 있습니다:

print(rag_docs[0].text)

결과:

NATIONAL ARTIFICIAL INTELLIGENCE 
RESEARCH AND DEVELOPMENT 
STRATEGIC PLAN 
2023 UPDATE

tagQdrant 벡터 데이터베이스 설정

이 글에서는 RAG 시스템의 데이터베이스를 구현하기 위해 Qdrant Vector Search Cloud를 사용할 것입니다. Qdrant의 무료 티어에는 1GB의 저장 공간이 포함되어 있어 이 튜토리얼에 충분합니다.

계속하기 전에 Qdrant Cloud 웹사이트에서 계정을 만들어야 합니다.

Vector Search Database | Qdrant Cloud
Managed cloud solution of the Qdrant vector search engine. Cloud-native vector database for high performant vector similarity search.
Qdrant Cloud

계정이 있고 로그인한 후에는 클러스터를 생성해야 합니다. Qdrant 웹사이트의 "quick start" 지침을 따라 무료 클러스터를 설정하고 API와 Qdrant 호스트 서버 이름을 받으세요.

Quickstart - Qdrant
Qdrant is an Open-Source Vector Database and Vector Search Engine written in Rust. It provides fast and scalable vector similarity search service with convenient API.
Edit on GitHub

키와 호스트네임을 변수에 저장하세요:

qdrant_api_key = "<your API key>"
qdrant_server = "https://<your server>"

다음으로, qdrant_client와 llama_index 패키지에서 관련 컴포넌트를 임포트해야 합니다:

import qdrant_client
from llama_index.vector_stores.qdrant import QdrantVectorStore

client = qdrant_client.QdrantClient(qdrant_server, api_key=qdrant_api_key)
vector_store = QdrantVectorStore(client=client, collection_name="NTSC")

이것은 무료 클러스터에 NTSC라는 이름의 컬렉션을 생성합니다.

메모리나 디스크에 로컬 데이터 저장소를 구성하고 web API를 통해 docker 컨테이너에서 자체 Qdrant 서버 인스턴스를 호스팅하는 방법에 대한 정보는 Qdrant 문서를 참조하세요.

tagRAG 시스템 완성하기

이제 LlamaIndex의 기본 코드를 사용하여 이러한 구성 요소들을 완전한 RAG 시스템으로 조립해보겠습니다:

from llama_index.core.query_engine import RetrieverQueryEngine
from llama_index.core.retrievers import VectorIndexRetriever
from llama_index.core.storage.storage_context import StorageContext
from llama_index.core import (
		VectorStoreIndex,
		ServiceContext,
		get_response_synthesizer,
)

# set up the service and storage contexts
service_context = ServiceContext.from_defaults(
    llm=mixtral_llm, embed_model=jina_embedding_model
)
storage_context = StorageContext.from_defaults(vector_store=vector_store)

# create an index
index = VectorStoreIndex.from_documents(
    rag_docs, storage_context=storage_context, service_context=service_context
)

# configure retriever
retriever = VectorIndexRetriever(
    index=index,
    similarity_top_k=2,
)

# configure response synthesizer
response_synthesizer = get_response_synthesizer(
    service_context=service_context,
    text_qa_template=qa_prompt,
    response_mode="compact",
)

# assemble query engine
query_engine = RetrieverQueryEngine(
    retriever=retriever,
    response_synthesizer=response_synthesizer,
)

이 시스템은 Jina Embeddings를 사용하여 텍스트 소스의 단락을 인덱싱하고 모든 프롬프트의 컨텍스트에 가장 일치하는 두 개의 결과를 포함시킵니다. 예를 들어 가장 일치하는 세 개의 결과로 변경하려면 위의 VectorIndexRetriever 초기화에서 similarity_top_k 매개변수만 수정하면 됩니다:

# configure retriever
retriever = VectorIndexRetriever(
    index=index,
    similarity_top_k=3,
)

이제 시스템을 사용할 준비가 되었습니다.

tag문서 쿼리하기

간단한 쿼리를 시도해보겠습니다:

response = query_engine.query("""
What is the Biden Administration's policy with regard to AI? 
""")
print(response.response)

결과 (귀하의 결과와 동일하지 않을 수 있습니다):

The Biden Administration prioritizes responsible AI systems that 
are ethical, trustworthy, and safe, and serve the public good. 
The Administration has committed to substantial funding for AI 
R&D, and has established the National AI Initiative Office to 
coordinate AI activities across the federal government. 

The Administration's AI policy focuses on developing evaluative
techniques for AI, workforce development, public-private
partnerships, and international collaboration in AI research.

더 구체적인 쿼리:

response = query_engine.query("""
What protections does the AI Bill of Rights propose to offer?
""")

print(response.response)
The AI Bill of Rights proposes five core protections: Safe and 
Effective Systems; Algorithmic Discrimination Protections; Data 
Privacy; Notice and Explanation; and Human Alternatives, 
Consideration, and Fallback.

또는 매우 구체적인 쿼리:

response = query_engine.query("Who is Kei Koizumi?")
print(response.response)
Kei Koizumi is the Principal Deputy Director for Policy at the Office 
of Science and Technology Policy (OSTP).

더 창의적인 질문도 할 수 있습니다:

response = query_engine.query("""
What rights will AI's receive under President Biden's proposed 
AI Bill of Rights?
""")
print(response.response)
The proposed AI Bill of Rights does not grant rights to AI systems, but 
rather outlines principles to ensure that AI technologies are 
developed and used in a manner that respects human rights and values. 
The principles include safety, transparency, fairness, disclosure, 
data privacy, non-discrimination, and the ability for individuals to 
opt out of certain AI systems.
response = query_engine.query("""
Why is President Biden's proposing an AI Bill of Rights?
Does AI really need rights?
""")
print(response.response)
President Biden's proposed AI Bill of Rights aims to ensure that AI 
technologies are developed and used ethically, legally, and with 
societal considerations in mind. The Bill of Rights is not granting 
"rights" to AI, but rather setting guidelines for the responsible 
development and deployment of AI systems to protect individuals and 
communities from potential negative impacts.
response = query_engine.query("""
Has Donald Trump weighed in on AI?
Will he Make Humans Great Again?
""")
print(response.response)
No information. The context information does not mention Donald 
Trump's views on AI.

tagJina AI와 Qdrant

Jina Embeddings의 8k 토큰 컨텍스트 윈도우는 훨씬 더 큰 텍스트 블록을 처리할 수 있어 검색 증강 생성에 특히 적합합니다. 다른 RAG 애플리케이션이 개별 문장이나 문장 쌍을 저장해야 하는 경우가 많은 반면, 이 튜토리얼에서는 크기를 걱정하지 않고 전체 단락을 사용할 수 있었습니다.

이는 동일한 정보를 전달하는 데 필요한 텍스트 항목의 수를 줄여 계산 비용을 낮추고, 메모리를 절약하며, 검색을 더 빠르게 만듭니다.

Qdrant의 벡터 데이터베이스는 구성이 간단하고, 빠르며, 비용 효율적이며, 보셨듯이 Python 코드 몇 줄만으로 RAG 시스템에 통합할 수 있습니다.

Qdrant의 AI 지원 데이터베이스와 클라우드 서비스에 대해 자세히 알아보려면 웹사이트를 방문하세요.

Qdrant - Vector Database
Qdrant는 Rust로 작성된 오픈소스 벡터 데이터베이스이자 벡터 검색 엔진입니다. 편리한 API로 빠르고 확장 가능한 벡터 유사도 검색 서비스를 제공합니다.
Vector Database

tag연락하기

Jina AI는 모든 규모와 유형의 기업에 신뢰할 수 있고 저렴한 AI 기술을 제공하기 위해 노력하고 있습니다. 귀하의 사용 사례에 대해 듣고 AI를 비즈니스 프로세스에 맞추는 데 도움을 드리고 싶습니다. Jina AI의 제품에 대한 자세한 정보와 연락처는 Jina AI 웹사이트를 확인하거나 Discord 커뮤니티에 참여하세요.

Jina AI - 최고의 임베딩과 완벽한 프롬프트
Jina AI는 최고 수준의 임베딩 API와 프롬프트 최적화 도구를 제공하여 멀티모달 AI 애플리케이션 개발을 용이하게 합니다.
Best Embeddings and Perfect Prompts
Jina AI Discord 서버에 참여하세요!
Discord의 Jina AI 커뮤니티를 확인해보세요 - 4493명의 다른 멤버들과 함께 무료 음성 및 텍스트 채팅을 즐기세요.
Discord
범주:
기술 블로그
rss_feed

자세히 보기
3월 11, 2026 • 7 분 소요
Bootstrapping Audio Embeddings from Multimodal LLMs
Han Xiao
Abstract illustration of a sound wave or heartbeat, formed by blue, orange, and gray dots on a white background.
3월 06, 2026 • 6 분 소요
Identifying Embedding Models from Raw Numerical Values
Han Xiao
Fingerprint illustration made from numbers, showcasing digital and high-tech design on a light background.
9월 09, 2025 • 11 분 소요
Multimodal Embeddings in Llama.cpp and GGUF
Andrei Ungureanu
Alex C-G
Cartoon llama in the center of a white background, emitting laser-like beams from its eyes. The illustration creates a playfu
현재 언어 / 테마
Search Foundation
Reader
Embeddings
Reranker
Jina API 키 받기
속도 제한
회사 소개
소식
Jina 로고 다운로드
open_in_new
Elastic 로고 다운로드
open_in_new
API 상태
Elastic © 2026.보안이용약관개인정보 보호쿠키 관리제 개인 정보를 판매하거나 공유하지 마세요.
본 웹사이트 및 관련 콘텐츠, 소프트웨어, 제품, 서비스는 전문가용으로만 제작되었습니다. 일반 소비자를 위한 것이 아니며, 소비자의 사용을 권장하지 않습니다.