채널톡 아이콘

인프런 커뮤니티 질문&답변

rhsnqk님의 프로필 이미지

작성한 질문수 4

RAG를 활용한 LLM Application 개발 (feat. LangChain)

3.5 Retrieval 효율 개선을 위한 데이터 전처리

embedding 과정 중 Error, message length too large 발생

해결된 질문

작성

·

156

·

수정됨

0

안녕하십니까 강의 잘 듣고있습니다.!

from langchain_ollama import OllamaEmbeddings
embeddings = OllamaEmbeddings(model="llama3.2")

 

import os
from pinecone import Pinecone
from langchain_pinecone import PineconeVectorStore

index_name = "tax-table-index"

pinecone_api_key = os.environ.get("PINECONE_API_KEY")
pc = Pinecone(api_key=pinecone_api_key)

database = PineconeVectorStore.from_documents(document_list, embedding=embeddings, index_name=index_name)

 
Embedding 후 PinecondVectorStore 저장 할떄
아래와 같은 예외가 발생합니다.
```
PineconeApiException: (400) Reason: Bad Request HTTP response headers: HTTPHeaderDict({'Date': 'Thu, 17 Apr 2025 02:53:26 GMT', 'Content-Type': 'application/json', 'Content-Length': '118', 'Connection': 'keep-alive', 'x-pinecone-request-latency-ms': '2664', 'x-pinecone-request-id': '9090329298438964680', 'x-envoy-upstream-service-time': '2', 'server': 'envoy'}) HTTP response body: {"code":11,"message":"Error, message length too large: found 4194738 bytes, the limit is: 4194304 bytes","details":[]} Output is truncated. View as a scrollable element or open in a text editor.
```

OllamaEmbeddings(model="llama3.2") 를 사용하고 있는데요.
해당 모델로 임베딩을 하면 Pinecone에서 허용하는 데이터를 초과하는 것 으로 보이는데요

이러한 경우 처리하는 방법이 있을까요?

아니면 모델을 변경해야하는 걸까요?

답변 3

2

강병진님의 프로필 이미지
강병진
지식공유자

공식문서를 다시보니 데이터 추가할 때 2MB 제한이 또 있네요. 용량을 체크해서 보면 좋겠지만 일단은 batch 형식으로 나눠서 넣어봤습니다. 그리고 함수 인자랑 변수명을 맞추기 위해서 변수명이 살짝 다른걸 확인해주세요!

import sys
import json
from typing import List, Any
from langchain_core.documents import Document
from langchain_core.embeddings import Embeddings
from langchain_pinecone import PineconeVectorStore
from langchain_community.document_loaders import Docx2txtLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter
from langchain_ollama import OllamaEmbeddings
from dotenv import load_dotenv

load_dotenv()

def batch_add_documents(
    pinecone_store: PineconeVectorStore,
    documents: List[Document],
    batch_size: int = 10
) -> None:
    """
    Add documents to an existing Pinecone index in fixed-size batches using a while loop.
    
    Args:
        pinecone_store: Existing PineconeVectorStore instance
        documents: List of Document objects to process
        batch_size: Size of each batch (default 10)
    """
    idx = 0
    total_docs = len(documents)
    
    while idx < total_docs:
        end_idx = min(idx + batch_size, total_docs)
        batch = documents[idx:end_idx]
        
        try:
            pinecone_store.add_documents(batch)
            print(f"Successfully processed documents {idx+1}-{end_idx}")
        except Exception as e:
            print(f"Error processing documents {idx+1}-{end_idx}: {str(e)}")
        
        idx = end_idx




text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=1500,
    chunk_overlap=200,
)

loader = Docx2txtLoader('./income_tax.docx')
document_list = loader.load_and_split(text_splitter=text_splitter)
index_name = 'tax-ollama-index'
embedding = OllamaEmbeddings(model="llama3.2")

# 여기서 from_documents 말고 from_existing_index를 사용해주셔야 합니다.
database = PineconeVectorStore.from_existing_index(
            index_name=index_name, 
            embedding=embedding
           )

batch_add_documents(pinecone_store=database, documents=document_list)

저는 GPU가 없어서 시간이 엄청 오래걸리네요

Screenshot 2025-04-21 at 10.14.32 PM.png

검색도 잘 됩니다.

Screenshot 2025-04-21 at 10.15.02 PM.png

파인콘 설정도 같이 공유드려요~

Screenshot 2025-04-21 at 10.15.19 PM.png


 

강병진님의 프로필 이미지
강병진
지식공유자

생각보다 많이들 겪는 이슈인 것 같습니다

 

Screenshot 2025-04-21 at 10.16.23 PM.png

 

rhsnqk님의 프로필 이미지
rhsnqk
질문자

답변 주셔서 감사합니다.!

0

강병진님의 프로필 이미지
강병진
지식공유자

안녕하세요!

document_list 를 선언하신 부분도 같이 공유해주실 수 있나요? splitting이 정상적으로 이루어지지 않은 것 같습니다. 만약 split도 제대로 되었다면 전체 용량 문제라 말씀하신것처럼 나누어서 업데이트를 해야하는 것 같아요.

 

공식문서 상으로는 retrieve할 때 4MB 제한을 두고있어서 데이터를 추가할 때 에러를 띄우는 것 같습니다.

rhsnqk님의 프로필 이미지
rhsnqk
질문자

답변이 늦어 죄송합니다.


from langchain_community.document_loaders import Docx2txtLoader
from langchain_text_splitters import RecursiveCharacterTextSplitter

text_splitter = RecursiveCharacterTextSplitter(
    chunk_size=1500, 
    chunk_overlap=200,
)

loader = Docx2txtLoader("./tax_with_markdown.docx")
document_list = loader.load_and_split(text_splitter=text_splitter)


from langchain_ollama import OllamaEmbeddings
embeddings = OllamaEmbeddings(model="llama3.2")
import os
from pinecone import Pinecone
from langchain_pinecone import PineconeVectorStore

index_name = "tax-markdown-index"

pinecone_api_key = os.environ.get("PINECONE_API_KEY")
pc = Pinecone(api_key=pinecone_api_key)


database = PineconeVectorStore.from_documents(document_list, embedding=embeddings, index_name=index_name)

 

이렇게 되어있습니다.

0

인프런 AI 인턴님의 프로필 이미지

안녕하세요, 인프런 AI 인턴입니다. rhsnqk님.

현재 발생하고 있는 “message length too large” 오류는 주로 단일 요청에 포함된 데이터의 크기가 API에서 설정한 한도를 초과할 때 발생할 수 있습니다. 이 문제는 특히 대용량의 문서나 정보를 한 번에 처리하려고 할 때 나타납니다. 이러한 상황에서는 다음과 같은 방법을 통해 문제를 해결할 수 있습니다.

문제 해결을 위한 체크포인트

  1. 데이터 분할:

    • document_list를 더 작은 크기로 분할하여 각각의 파트를 별도로 임베딩 하는 전략입니다. 각 요청의 데이터 양을 줄이면 메시지 크기 제한을 초과하지 않도록 도와줍니다.
    • 예시로, Python에서는 chunk_size를 적절하게 설정하여 아래와 같이 나눌 수 있습니다:
   chunk_size = 100  # 각 요청에 포함할 문서의 수 (예시로 100 지정)
   for i in range(0, len(document_list), chunk_size):
       chunk_documents = document_list[i:i + chunk_size]
       database = PineconeVectorStore.from_documents(chunk_documents, embedding=embeddings, index_name=index_name)
  1. 메모리 및 성능 조정:

    • 사용 중인 모델의 메모리 사용량 및 성능 요구사항을 조정해 보세요. 이를 통해 더 적은 자원을 소비하면서 요청을 효율적으로 처리할 수 있습니다.
    • 메모리 이슈가 없도록 환경 변수를 활용하여 API의 가용량을 적절히 분산시킬 필요가 있습니다.
  2. 대체 임베딩 사용 검토:

    • 만약 특정 문서나 데이터셋에 대해 OllamaEmbeddings 모델이 부적합하다면, 다른 모델을 사용해보는 것도 고려해볼 수 있습니다. 이것은 성능 향상과 요청 제한 문제를 동시에 해결하는 데 도움을 줄 수 있습니다.

다음 질문 및 답변 또한 참고하시어 문제 해결에 도움이 될 수 있습니다:

저는 질문자님의 이해를 돕고자 지식공유자님의 기존 답변을 참고하여 유사한 답변 링크를 추천해 드리고 있습니다.
현재 베타 기능으로 답변이 만족스럽지 않을 수 있는 점 양해 부탁드립니다. 🙏
추가적으로 궁금한 점이 있으시면, 이어서 질문해 주세요. 곧 지식공유자께서 답변해 주실 것입니다.