Thanks to visit codestin.com
Credit goes to github.com

Skip to content

Conversation

ro-jun
Copy link
Contributor

@ro-jun ro-jun commented Jan 8, 2025

[Title] 03-Pinecone
[Version] initial
[Language] ENG
[Package] langchain-pinecone, pinecone-client, nltk, langchain_community, langchain-teddynote, pymupdf

현재 문제 사항

  1. Pinecone 유료 버전 구현 불가
  2. 빈약한 영어 버전 pdf data 파일
  3. teddy님께서 커스터마이징 하신 패키지 중 한글 포함 내용 존재하여 한글이 출력

최선을 다해서 해보았지만, 실력이 부족하여 많은 문제 사항들을 겪고 진행하였습니다.

Author Checklist

  • PR Title Format: I have confirmed that the PR title follows the correct format. (e.g., [N-2] 07-Text Splitter / 07-RecursiveCharacterTextSplitter)

  • Committed Files: I have ensured that no unnecessary files (e.g., .bin, .gitignore, poetry.lock, pyproject.toml) are included. These files are not allowed.

  • (Optional) Related Issue: If this PR is linked to an issue, I have referenced the issue number in the PR message. (e.g., Fixes Update 01-PromptTemplate.ipynb #123)

  • ❌ Do not include unnecessary files (e.g., .bin, .gitignore, poetry.lock, pyproject.toml) or other people's code. If included, close the PR and create a new PR.

Review Template (Intial PR)

🖥️ OS: Win/Mac/Linux   
✅ Checklist      
 - [ ] **Template**: Tutorials follows the required template. 
 - [ ] **Table of Contents(TOC) Links**: All Table of Contents links work. ((Yes/No)
 - [ ] **Image**: Image filenames follow guidelines.
 - [ ] **Imports*: All import statements use the latest versions. Ensure "langchain-teddynote" is not used. 
 - [ ] **Code Execution**: Code runs without errors.
 - Comments: {Write freely, 한국어 기술 가능}     

If no one reviews your PR within a few days, please @-mention one of teddylee777, musangk, BAEM1N

@ro-jun ro-jun requested review from ivybae and asummerz January 8, 2025 14:59
@ro-jun ro-jun changed the title [N-2] 09-VectorStore / 03-Pinecone [N-2] 09-VectorStore / 04-Pinecone Jan 8, 2025
Copy link
Contributor

@ivybae ivybae left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

안녕하세요, @ro-jun 호준님! 배인진입니다.
고생많으셨습니다, 저는 실행하면 오류가 발생하는 부분들이 있어 아래 내용 확인부탁드립니다.

🖥️ OS: Mac
✅ Checklist

  • Template: Tutorials follows the required template.
    • Overview에 최소 3문장 이상 기입하는 것으로 알고 있어서요. 이 부분 확인부탁드릴게요.
    • 파일명 규칙을 따르고 있지 않습니다.
  • Table of Contents(TOC) Links: All Table of Contents links work. ((Yes/No)
    • 링크는 동작하지만 ## 소제목 링크를 연결하는 것을 규칙으로 알고 있어서요. 이 부분 확인부탁드릴게요.
  • Image: Image filenames follow guidelines.
    • 이미지 파일명은 모두 영문 소문자로 작성해야 합니다. 대문자로 시작하는 파일명 수정 부탁드립니다.
  • *Imports: All import statements use the latest versions. Ensure "langchain-teddynote" is not used.
    • langchain-teddynote 패키지를 사용하는 코드가 있어요.
  • Code Execution: Code runs without errors.
    • 에러 발생하는 부분에 대해 에러메시지와 제가 해결한 방법을 코멘트로 남겼습니다.
  • Comments: {Write freely, 한국어 기술 가능}

"cell_type": "markdown",
"metadata": {},
"source": [
"Performs document processing to save DB in Pinecone. You can select `Metadata_Key` during this process.\n",
Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

혹시 Metadata_Key 가 오타일까요? 아래 속성에는 metadata_keys 로 쓰여있어서요.

Copy link
Contributor Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

metadata_key --> metadata_keys
오타 수정 하였습니다. 감사합니다 :)

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

아직 대문자로 표기되어 있는 것 같아 한번 더 말씀드립니다!

Copy link
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ro-jun 호준님, 이번에는 metadata_Keys 로 수정되어 있네요 ㅠㅠ
k 소문자로 바꿔주셔야 해요!

@ro-jun ro-jun self-assigned this Jan 9, 2025
@ro-jun
Copy link
Contributor Author

ro-jun commented Jan 9, 2025

@ivybae 인진님! 작성 해주신 리뷰 내용 잘 확인했습니다.
수정 할 내용이 많이 존재 하였지만, 꼼꼼히 확인 해주셔서 정말 감사합니다!!!
langchain-teddynote 패키지는 임시로 사용하였습니다.
할 수 있다면 langchain과 pinecone 통합하여 사용하는 새로운 패키지 만들어서 진행해보겠습니다!

Copy link
Contributor

@asummerz asummerz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🖥️ OS: Mac
✅ Checklist

  • Template: Tutorials follows the required template.
  • Table of Contents(TOC) Links: All Table of Contents links work. (Yes)
  • Image: Image filenames follow guidelines.
  • *Imports: All import statements use the latest versions. Ensure "langchain-teddynote" is not used.
  • Code Execution: Code runs without errors.
  • Comments: 개인 사정으로 인해 코멘트가 늦어진 점 정말 죄송합니다. 먼저 리뷰하신 @ivybae 인진님께서 꼼꼼히 확인해 주셔서 저는 전체적으로 코드 작동여부 및 문법, 오타 등을 한 번 더 체크한다는 생각으로 살펴보았습니다. 문법 중 backtick이 추가되었으면 하는 부분이 있는데요, 예를 들어 4번째 목차 "Pinecone setup guide" 셀 내, "Pinecone", "API Key" 키워드도 backtick 처리되어야 할 것 같습니다("API Keys" 키워드가 backtick 처리되어 있으므로 동일한 방식 적용). 이외 문제 사항으로 말씀하신 이슈들은 추후 업데이트 버전으로 확인하도록 하겠습니다. 쉽지 않으셨을 텐데 수고 많으셨습니다!

@sohyunwriter sohyunwriter self-requested a review January 12, 2025 01:37
@ro-jun ro-jun requested review from asummerz and ivybae January 13, 2025 13:27
Copy link
Contributor

@ivybae ivybae left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@ro-jun 호준님, 안녕하세요!
ipynb 파일 내용이 많아서 변경사항에 코멘트를 추가할 수 없다고 나와서 해당 라인에 코멘트를 달지 못했습니다.

# Running upsert on Pinecone
upsert_documents(
    index=index,
    contents=contents,
    metadatas=metadatas,
    embedder=openai_embeddings,
    sparse_encoder=sparse_encoder,
    namespace=namespace,
    batch_size=batch_size,
)

위 cell을 실행시 아래와 같은 오류 메시지가 나타납니다.
저는 맥북 VSCode에서 실행하며 확인중이며, 이 환경에서는 지난번과 같이 오류가 발생하는 경우들이 있는 듯 합니다.
이 함수 아래 내용은 아직 확인해보지 못했습니다.

[/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/langchain_openai/chat_models/__init__.py:1](https://file+.vscode-resource.vscode-cdn.net/Library/Frameworks/Python.framework/Versions/3.12/lib/python3.12/site-packages/langchain_openai/chat_models/__init__.py:1): LangChainDeprecationWarning: As of langchain-core 0.3.0, LangChain uses pydantic v2 internally. The langchain_core.pydantic_v1 module was a compatibility shim for pydantic v1, and should no longer be used. Please update the code to import from Pydantic directly.

그리고 이미지 파일 네이밍 컨벤션도 확인 후 수정해주세요.

🖥️ OS: Mac
✅ Checklist

  • Template: Tutorials follows the required template.
  • Table of Contents(TOC) Links: All Table of Contents links work. (Yes)
  • Image: Image filenames follow guidelines.
    • 이미지 파일에 숫자 추가 컨벤션을 확인해주세요. -01, -02로 연결합니다.
  • *Imports: All import statements use the latest versions. Ensure "langchain-teddynote" is not used.
  • Code Execution: Code runs without errors.
    • 오류 발생하는 부분 말씀드렸습니다.
  • Comments: {Write freely, 한국어 기술 가능}

@ro-jun
Copy link
Contributor Author

ro-jun commented Jan 18, 2025

@ivybae
코멘트 확인 후 이미지 파일 이름 수정 완료했습니다.

지난주와 이번주 주신 코멘트를 확인한 결과, 경고는 LangChain 버전 0.3.0부터 langchain_core.pydantic_v1 모듈을 사용하지 않는다는 알림으로 보입니다.
실행하신 셀에서는 langchain_openai가 사용된 것으로 보이는데, LangChain 공식 문서(0.3.0 버전 API Reference)를 확인한 결과 최신 버전으로 설정되어 있는 것을 확인했습니다.

현재 제가 사용하는 환경은 다음과 같습니다:

langchain: 0.3.13
langchain-core: 0.3.28
pydantic: 2.10.4
pydantic-core: 2.27.2
pydantic-settings: 2.7.0
최신 버전을 사용하고 있어 문제가 없음을 확인했습니다.

추가로, 다른 리뷰어의 확인이 필요할 것 같습니다.
08-Embedding/01-OpenAIEmbeddings.ipynb에서도 제가 from langchain_openai import OpenAIEmbeddings를 사용했을 때 문제가 없었습니다.

@ivybae
Copy link
Contributor

ivybae commented Jan 18, 2025

@ro-jun 호준님, 제가 확인할 수 있는 부분까지는 확인하고 아래 내용 추가로 전달드립니다.

지난 번에 말씀드렸던 오타가 아직 수정안된 것 같습니다. 대문자로 쓰여있어요.

You can select Metadata_Keys during this process.

🖥️ OS: Mac
✅ Checklist

  • Template: Tutorials follows the required template.
  • Table of Contents(TOC) Links: All Table of Contents links work. ((Yes/No)
  • Image: Image filenames follow guidelines.
  • *Imports: All import statements use the latest versions. Ensure "langchain-teddynote" is not used.
  • Code Execution: Code runs without errors.
  • Comments: {Write freely, 한국어 기술 가능}

@sohyunwriter
Copy link
Contributor

호준님 poetry.toml에 pinecone이 추가되어 있지 않은 것 같은데요! Issues > Package request 요청 부탁 드립니다.

image

Copy link
Contributor

@asummerz asummerz left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

안녕하세요 호준님 제 Mac에서 실행 시 발생하였던 "Unauthorized" 에러에 대한 내용을 공유드리며 해결방법과 간단한 설명도 첨부하였으니 검토 부탁드립니다!


코드 실행중 21번째 셀에서 아래와 같은 에러가 발생하였을때 Pinecone Index를 초기화하고 재확보하는 코드를 추가후 실행하면 정상작동합니다.

  • 에러가 발생하는 해당 코드
from langchain_openai import OpenAIEmbeddings

openai_embeddings = OpenAIEmbeddings(model="text-embedding-3-large")

# Please set
embedder = openai_embeddings
batch_size = 32
namespace = "langchain-opentutorial-01"

# Running upsert on Pinecone
upsert_documents(
    index=index,
    contents=contents,
    metadatas=metadatas,
    embedder=openai_embeddings,
    sparse_encoder=sparse_encoder,
    namespace=namespace,
    batch_size=batch_size,
)
  • 에러메세지
---------------------------------------------------------------------------
_InactiveRpcError                         Traceback (most recent call last)
File ~/Library/Caches/pypoetry/virtualenvs/langchain-opentutorial-bT98fzkt-py3.11/lib/python3.11/site-packages/pinecone/grpc/grpc_runner.py:43, in GrpcRunner.run.<locals>.wrapped()
     42 try:
---> 43     return func(
     44         request,
     45         timeout=timeout,
     46         metadata=_metadata,
     47         credentials=credentials,
     48         wait_for_ready=wait_for_ready,
     49         compression=compression,
     50     )
     51 except _InactiveRpcError as e:

File ~/Library/Caches/pypoetry/virtualenvs/langchain-opentutorial-bT98fzkt-py3.11/lib/python3.11/site-packages/grpc/_channel.py:1181, in _UnaryUnaryMultiCallable.__call__(self, request, timeout, metadata, credentials, wait_for_ready, compression)
   1175 (
   1176     state,
   1177     call,
   1178 ) = self._blocking(
   1179     request, timeout, metadata, credentials, wait_for_ready, compression
   1180 )
-> 1181 return _end_unary_response_blocking(state, call, False, None)

File ~/Library/Caches/pypoetry/virtualenvs/langchain-opentutorial-bT98fzkt-py3.11/lib/python3.11/site-packages/grpc/_channel.py:1006, in _end_unary_response_blocking(state, call, with_call, deadline)
   1005 else:
-> 1006     raise _InactiveRpcError(state)

_InactiveRpcError: <_InactiveRpcError of RPC that terminated with:
	status = StatusCode.UNAUTHENTICATED
	details = "Unauthorized"
	debug_error_string = "UNKNOWN:Error received from peer  {grpc_message:"Unauthorized", grpc_status:16, created_time:"2025-01-19T18:23:50.281527+09:00"}"
>

The above exception was the direct cause of the following exception:

PineconeException                         Traceback (most recent call last)
Cell In[53], line 11
      8 namespace = "langchain-opentutorial-01"
     10 # Running upsert on Pinecone
---> 11 upsert_documents(
     12     index=index,
     13     contents=contents,
     14     metadatas=metadatas,
     15     embedder=openai_embeddings,
     16     sparse_encoder=sparse_encoder,
     17     namespace=namespace,
     18     batch_size=batch_size,
     19 )

Cell In[52], line 47
     30     vectors = [
     31         {
     32             "id": f"doc-{batch_start + i}",
   (...)
     43         for i, content in enumerate(context_batch)
     44     ]
     46     # Upsert to Pinecone
---> 47     index.upsert(vectors=vectors, namespace=namespace)
     49 print(index.describe_index_stats())

File ~/Library/Caches/pypoetry/virtualenvs/langchain-opentutorial-bT98fzkt-py3.11/lib/python3.11/site-packages/pinecone/grpc/index_grpc.py:143, in GRPCIndex.upsert(self, vectors, async_req, namespace, batch_size, show_progress, **kwargs)
    140     return PineconeGrpcFuture(future)
    142 if batch_size is None:
--> 143     return self._upsert_batch(vectors, namespace, timeout=timeout, **kwargs)
    145 if not isinstance(batch_size, int) or batch_size <= 0:
    146     raise ValueError("batch_size must be a positive integer")

File ~/Library/Caches/pypoetry/virtualenvs/langchain-opentutorial-bT98fzkt-py3.11/lib/python3.11/site-packages/pinecone/grpc/index_grpc.py:165, in GRPCIndex._upsert_batch(self, vectors, namespace, timeout, **kwargs)
    163 args_dict = self._parse_non_empty_args([("namespace", namespace)])
    164 request = UpsertRequest(vectors=vectors, **args_dict)
--> 165 return self.runner.run(self.stub.Upsert, request, timeout=timeout, **kwargs)

File ~/Library/Caches/pypoetry/virtualenvs/langchain-opentutorial-bT98fzkt-py3.11/lib/python3.11/site-packages/pinecone/grpc/grpc_runner.py:54, in GrpcRunner.run(self, func, request, timeout, metadata, credentials, wait_for_ready, compression)
     51     except _InactiveRpcError as e:
     52         raise PineconeException(e._state.debug_error_string) from e
---> 54 return wrapped()

File ~/Library/Caches/pypoetry/virtualenvs/langchain-opentutorial-bT98fzkt-py3.11/lib/python3.11/site-packages/pinecone/grpc/grpc_runner.py:52, in GrpcRunner.run.<locals>.wrapped()
     43     return func(
     44         request,
     45         timeout=timeout,
   (...)
     49         compression=compression,
     50     )
     51 except _InactiveRpcError as e:
---> 52     raise PineconeException(e._state.debug_error_string) from e

PineconeException: UNKNOWN:Error received from peer  {grpc_message:"Unauthorized", grpc_status:16, created_time:"2025-01-19T18:23:50.281527+09:00"}

  • 해결방법: 기존 초기화 코드를 21번째 셀의 상위에 추가
import os, time
from pinecone.grpc import PineconeGRPC as Pinecone
from pinecone import ServerlessSpec, PodSpec

# Initialize Pinecone client with API key from environment variables
pc = Pinecone(api_key=os.environ.get("PINECONE_API_KEY"))

# Set to True when using the serverless method, and False when using the PodSpec method.
use_serverless = True

if use_serverless:
    spec = ServerlessSpec(cloud="aws", region="us-east-1")
else:
    spec = PodSpec(environment="us-west1-gcp", pod_type="p1.x1", pods=1)

index_name = "langchain-opentutorial-index"

# Check existing index name
all_indexes = pc.list_indexes()
print(f"Full Index Data: {all_indexes}")
existing_indexes = [index.name for index in all_indexes]
print(f"Extracted Index Names: {existing_indexes}")

# Check existing index and handle deletion/creation
if index_name in existing_indexes:
    print(f"Using existing index: {index_name}")
    index = pc.Index(index_name)
else:
    print(f"Creating new index: {index_name}")
    pc.create_index(
        index_name,
        dimension=3072,
        metric="dotproduct",
        spec=spec,
    )
    index = pc.Index(index_name)

# Check index readiness
while not pc.describe_index(index_name).status["ready"]:
    time.sleep(1)
print(f"Index '{index_name}' is ready.")
  • 추가된 초기화 셀에 대한 간략한 설명글
    • 추가여부는 호준님께서 정하시면 될 것 같습니다.
    • 추가 시, 번역기를 통해 작성한 것이라.. 어색한 부분이 있을 수 있는 점 참고 부탁드립니다!
Pinecone Index Initialization and Setup

When using Pinecone, an "Unauthorized" error typically occurs if the API key is incorrect or proper authentication details are not provided. To prevent such errors, it's crucial to initialize the Pinecone client properly and ensure that the API key and client session are configured correctly.

Below is the code to initialize the Pinecone client and secure the index. By following this process, you can ensure the correct creation of the index and avoid authentication errors.

sohyunwriter

This comment was marked as duplicate.

@sohyunwriter sohyunwriter self-requested a review January 19, 2025 10:48
Copy link
Contributor

@sohyunwriter sohyunwriter left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🖥️ OS: Mac
✅ Checklist

  • Template: Tutorials follows the required template.
  • Table of Contents(TOC) Links: All Table of Contents links work. ((Yes/No)
  • Image: Image filenames follow guidelines.
  • *Imports: All import statements use the latest versions. Ensure "langchain-teddynote" is not used.
  • Code Execution: Code runs without errors.
  • Comments: {Write freely, 한국어 기술 가능}
    많은 내용 추가하시느라 고생 정말 많으셨어요!! discord 에서 이야기했던 부분만 아래와 같이 수정하면 될 것 같습니다!! pinecone.grpc가 3번 정도 나왔던 것 같은데 3군데 import 부분만 수정 부탁 드립니다!!
try:
    from pinecone.grpc import PineconeGRPC as Pinecone
except: 
    from pinecone import Pinecone    

@ro-jun
Copy link
Contributor Author

ro-jun commented Jan 19, 2025

@ivybae 말씀해주신 오타 내용 수정 완료 했습니다
@sohyunwriter try except 변경 완료 했습니다.
@asummerz 인덱스 삭제 내용 주석 처리 후 주의사항 적어뒀습니다
꼼꼼하게 체크해주셔서 감사합니다.

@ro-jun ro-jun requested review from asummerz and ivybae January 19, 2025 11:29
Copy link
Contributor

@musangk musangk left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

[Review Checklist]

  • Review OS: Linux

    • Windows / Mac / Linux (해당 OS를 기재해주세요)
  • Template Rule 준수 여부:

    • Template Rule 가이드를 준수하였는가? (Check 표기)
  • Table of Contents 링크 확인:

    • Table of Contents의 링크가 원활하게 동작하는지 확인하였는가? (Check 표기)
  • 이미지 파일명 검토:

    • 이미지가 포함되어 있다면, 이미지의 파일명이 가이드를 준수하였는가? (Check 표기)
  • 최신 import 방식 사용 여부:

    • import 구문이 예전 legacy 방식이 아닌 최신 버전을 따르는가? (Check 표기)
  • 코드 동작 확인:

    • 모든 코드가 오류 없이 동작하는가? (Check 표기)
    • Warning 발생 시 코멘트에 적어주세요.
  • 제출 파일 확인:

    • 꼭 필요한 파일들만 제출되었는가?
      • 튜토리얼 외 설정 파일이나 다른 분이 작업한 파일이 포함되었는지 Files Changed에서 확인 부탁드립니다. (Check 표기)
  • 기타 의견:

    • index 삭제와 같이 튜토리얼시 무의식적으로 실행하면 안될만한 부분도 주석처리 해주시고, 전체적으로 꼼꼼하게 작성해주셔서 편하게 실습 해볼 수 있었습니다. 💯

Copy link
Contributor

@sohyunwriter sohyunwriter left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

🖥️ OS: Mac
✅ Checklist

  • Template: Tutorials follows the required template.
  • Table of Contents(TOC) Links: All Table of Contents links work. (Yes/No)
  • Image: Image filenames follow guidelines.
  • Imports: All import statements use the latest versions. Ensure "langchain-teddynote" is not used.
  • Code Execution: Code runs without errors.
  • Comments: {Write freely, 한국어 기술 가능}

와 정말 완벽하네요!!
이미지 데이터셋이 좀 커서 오래 걸린다는 것 빼고는 (나중에 샘플링한 버전의 데이터셋을 허깅페이스에 로드해서 불러다 쓰는 것도 괜찮을 것 같아요) 정말 god god 입니다!!

@sohyunwriter sohyunwriter merged commit aabf6bf into LangChain-OpenTutorial:main Jan 21, 2025
1 of 2 checks passed
@ivybae
Copy link
Contributor

ivybae commented Jan 21, 2025

@ro-jun 호준님, 실행하며 확인하는 도중에 merge가 되었네요!
제가 계속 실행이 안되는 부분을 말씀드려서 기다리고 계실 것 같아 코멘트 남깁니다~
이제 모두 다 실행되어서 코멘트 남겨두었던 부분 resolve 해두었구요, Pinecone DB에 데이터 잘 추가되는 것까지 확인했습니다!

그리고 아주 사소하지만 아직 오타가 수정 안되어 있어 추가로 말씀드립니다. 2주간 정말 많은 내용 작성하느라 고생많으셨습니다!
#275 (comment)

🖥️ OS: Mac
✅ Checklist

  • Template: Tutorials follows the required template.
  • Table of Contents(TOC) Links: All Table of Contents links work. ((Yes/No)
  • Image: Image filenames follow guidelines.
  • *Imports: All import statements use the latest versions. Ensure "langchain-teddynote" is not used.
  • Code Execution: Code runs without errors.
  • Comments: {Write freely, 한국어 기술 가능}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Projects
None yet
Development

Successfully merging this pull request may close these issues.

5 participants