"라마 인덱스 라이브러리에서도 openai를 임포트할 수 있어요."
LlamaIndex 라마 인덱스가 뭔데!!
LlamaIndex (또는 llama_index) 라이브러리를 말함. 대규모 언어 모델(LLM)을 사용하여 구조화되지 않은 데이터를 쉽게 처리할 수 있게 해주는 데이터 프레임워크. 문서 인덱싱, 쿼리 처리, 데이터 구조화 등의 기능을 제공.
아! 그냥 라이브러리 이름이였구나. 인덱스가 붙어서 뭔가 했네.
어쨌든 라마 인덱스를 써서 RAG도 해야하는데...
from llama_index.llms.openai import OpenAI
from llama_index.core.llms import ChatMessage
client_llama = OpenAI(model = 'gpt-3.5-turbo')
message = [ChatMessage(role="user", content="안녕! 넌 누구야?")]
response = client_llama.chat(message)
response #대체 왜 안되는지 모르겠음
Retrying llama_index.llms.openai.base.OpenAI._chat in 0.7542383406381253 seconds as it raised APIConnectionError: Connection error..
Retrying llama_index.llms.openai.base.OpenAI._chat in 1.829488323159351 seconds as it raised APIConnectionError: Connection error..
API에러라니!!! openai 라이브러리에서는 다 잘 됐잖아 왜 얘만 안되는거야. 이거 붙잡고 한 시간은 끙끙거리다가 클로드랑 대화하다가 우연히(?) 때려맞추기 성공! 아래 코드에서 빨간색 코드가 추가된 것.
api키 커넥션이 자꾸 문제라길래 client_llama 부분에 api_key를 넣어줬더니 된다. 왜 강의 자료랑 다른건데..
import os
from llama_index.llms.openai import OpenAI
from llama_index.core.llms import ChatMessage
api_key = " "
client_llama = OpenAI(api_key=api_key, model = 'gpt-3.5-turbo')
message = [ChatMessage(role="user", content="안녕! 넌 누구야?")]
response = client_llama.chat(message)
response
response.message.content #결과값만 깔끔하게 나오게
어쨌든 되니까 넘어간다.
빠르고 간편하게 결과만 보고 싶을 때 = 라마인덱스
지난 번 포스팅에서 했던 것과 똑같이 오픈ai 위키백과 페이지를 참조해서 답변을 받아보자.
2024.08.06 - [Upstage AI Lab 4기 학습일지] - 8/6 학습일지 | 파이썬에서 RAG 구현하기
원래 되야했던 코드 (강의에서는 잘만 실행되는 코드)
#참조할 text파일(오픈에이아이에 관한 위키문서)
import requests
response = requests.get(
"https://en.wikipedia.org/w/api.php",
params = {
"action": "query",
"format": "json",
"titles": "OpenAI",
"prop": "extracts",
"explaintext": True
}
).json()
page = next(iter(response['query']['pages'].values()))
text = page['extract']
#위키문서를 openai.txt로 저장함
from pathlib import Path
data_path = Path("../dataset/llamaindex_data")
if not data_path.exists():
Path.mkdir(data_path)
with open(f"{data_path}/openai.txt", "w") as fp:
fp.write(text)
#라마인덱스로 쿼리 엔진을 만들어서 간편하게 질문(이 되야 하는데!)
import os
from llama_index.core import VectorStoreIndex, SimpleDirectoryReader
documents = SimpleDirectoryReader("../dataset/llamaindex_data").load_data()
# 이렇게 읽어온 다큐멘트를 사용해서 인덱스를 만들어준다
vector_index = VectorStoreIndex.from_documents(documents)
# 이 인덱스를 통해 쿼리 엔진을 만들어준다
query_engine = vector_index.as_query_engine()
query = "OpenAI의 sora 모델에 대해서 설명해줘"
response = query_engine.query(query)
print(response)
근데 이놈의 api 에러가 계속 난다. ㅂㄷㅂㄷ 강의 따라가면서 똑같이 쳐도 아래 에러가 반복됨.
Retrying llama_index.llms.openai.base.OpenAI._chat in 0.0626763020872173 seconds as it raised APIConnectionError: Connection error..
Retrying llama_index.llms.openai.base.OpenAI._chat in 0.2854151149825639 seconds as it raised APIConnectionError: Connection error..
---------------------------------------------------------------------------
LocalProtocolError Traceback (most recent call last)
..
APIConnectionError : Connection error.
API를 다시 집어넣어보고, openai 임베딩을 다시 해봤지만 안됨..
어찌어찌 클로드가 제시해준 방법 중에 아래꺼를 해봤는데 결과가 나오긴 나온다!
-> 서비스 컨텍스트 설정: VectorStoreIndex를 생성할 때 서비스 컨텍스트를 통해 임베딩 모델을 지정할 수 있습니다.
허깅페이스 어디서 많이 들어는 봤는데 뭔지 전혀 모르던 아이를 이렇게 쓸 줄이야.
일단 써보라니까 씁니다..
import os
from llama_index.core import ServiceContext, VectorStoreIndex
from llama_index.embeddings.huggingface import HuggingFaceEmbedding
embed_model = HuggingFaceEmbedding(model_name="sentence-transformers/all-MiniLM-L6-v2")
service_context = ServiceContext.from_defaults(embed_model=embed_model)
vector_index = VectorStoreIndex.from_documents(
documents,
service_context=service_context
)
# 이 인덱스를 통해 쿼리 엔진을 만들어준다
query_engine = vector_index.as_query_engine()
query = "OpenAI의 sora 모델에 대해서 설명해줘"
response = query_engine.query(query)
print(response)
소라에 대해 설명을 해주기는 하는데, 뭔가 잔소리가 많다. 일단 복붙함. 잔소리 끝에 소라에 대해 알려줌.
/Users/alookso/study/RAG_0806/.venv/lib/python3.12/site-packages/tqdm/auto.py:21: TqdmWarning: IProgress not found. Please update jupyter and ipywidgets. See https://ipywidgets.readthedocs.io/en/stable/user_install.html from .autonotebook import tqdm as notebook_tqdm /var/folders/tx/bcbxk5bj33x4r2rt041m7bmr0000gn/T/ipykernel_69276/235737232.py:7: DeprecationWarning: Call to deprecated class method from_defaults. (ServiceContext is deprecated, please use `llama_index.settings.Settings` instead.) -- Deprecated since version 0.10.0. service_context = ServiceContext.from_defaults(embed_model=embed_model)
The Sora model by OpenAI is a text-to-video model that is currently available for red teams to manage critical harms and risks. It was announced on February 15, 2024, with plans for a public release at an unspecified date.
클로드 해석
이 출력은 몇 가지 경고와 정보를 포함하고 있습니다. 각 부분을 설명해드리겠습니다:
1. TqdmWarning:
- 이는 Jupyter 환경에서 사용되는 진행 바(progress bar) 라이브러리인 tqdm과 관련된 경고입니다.
- jupyter와 ipywidgets를 업데이트하라고 제안하고 있습니다.
2. DeprecationWarning:
- LlamaIndex 라이브러리의 `ServiceContext.from_defaults()` 메소드가 더 이상 사용되지 않음(deprecated)을 알리는 경고입니다.
- 대신 `llama_index.settings.Settings`를 사용하라고 제안하고 있습니다.
이 출력은 사용 중인 라이브러리들의 몇 가지 경고와 함께, 아마도 당신이 질문한 내용에 대한 AI의 응답(Sora 모델에 대한 정보)을 포함하고 있습니다. 경고들은 사용 중인 라이브러리의 버전 업데이트나 코드 수정이 필요할 수 있음을 나타내지만, 프로그램의 기능에 직접적인 영향을 미치지는 않을 수 있습니다.
+추가
허깅페이스 없이 api키 다시 넣어서 해결!!!
from llama_index.core import Settings
Settings._llm
를 해보니 api_key='' 빈칸이다! 안들어간 것. 이걸 넣어주면 되겠구나!
import os
from llama_index.core import VectorStoreIndex, Settings
from llama_index.llms.openai import OpenAI
#from llama_index.llms import OpenAI 클로드가 잘못 알려준듯?
# API 키 설정 (환경 변수 사용)
os.environ["OPENAI_API_KEY"] = "your-api-key-here"
# 또는 Settings 객체에 직접 설정
Settings.llm = OpenAI(model="gpt-3.5-turbo")
Settings.embed_model = "default" # 또는 다른 임베딩 모델 지정
documents = SimpleDirectoryReader("../dataset/llamaindex_data").load_data()
vector_index = VectorStoreIndex.from_documents(documents)
query_engine = vector_index.as_query_engine()
query = "OpenAI의 sora 모델에 대해서 설명해줘"
response = query_engine.query(query)
print(response)
결과값을 받았다.
이렇게 라마인덱스는 파이썬에서 겨우 몇 줄 만으로 간편하게 RAG 프로세스를 만들 수 있다는 장점이 있다.
라마인덱스의 커스터마이징 하는 법은 다음 편에 계속 -
'공부방 > Upstage AI Lab 4기' 카테고리의 다른 글
8/8~9 학습일지 | Github랑 Git이 다른 거였어?! (0) | 2024.08.09 |
---|---|
패스트캠퍼스 Upstage AI Lab 부트캠프 4기, "지원부터 OT까지, 초반부 진행 후기" (0) | 2024.08.09 |
8/6 학습일지 | 파이썬에서 RAG 구현하기 (0) | 2024.08.06 |
네이버 증권 데이터 크롤링 | f-string이 중요하네!! 디버깅 힌트 (0) | 2024.08.06 |
RAG 발전에 중요한 영향을 끼친 3가지 논문 (0) | 2024.08.05 |