Langfuse를 사용하여 RAG에서 쿼리 추적하기
이 문서는 Langfuse를 사용해 RAG에서 쿼리를 추적하는 방법을 보여주는 간단한 쿡북입니다. RAG 파이프라인은 문서를 저장하고 검색하기 위해 LlamaIndex와 Milvus Lite로 구현됩니다.
이 빠른 시작에서는 Milvus Lite를 벡터 저장소로 사용하여 LlamaIndex 애플리케이션을 설정하는 방법을 보여드리겠습니다. 또한 Langfuse LlamaIndex 통합을 사용하여 애플리케이션을 추적하는 방법도 보여드리겠습니다.
Langfuse는 팀이 LLM 애플리케이션을 공동으로 디버그, 분석 및 반복할 수 있도록 지원하는 오픈 소스 LLM 엔지니어링 플랫폼입니다. 모든 플랫폼 기능이 기본적으로 통합되어 개발 워크플로를 가속화합니다.
Milvus Lite는 벡터 임베딩 및 유사성 검색을 통해 AI 애플리케이션을 지원하는 오픈 소스 벡터 데이터베이스인 Milvus의 경량 버전입니다.
설정
llama-index
및 langfuse
이 모두 설치되어 있는지 확인합니다.
$ pip install llama-index langfuse llama-index-vector-stores-milvus --upgrade
연동을 초기화합니다. Langfuse 프로젝트 설정에서 API 키를 가져와 public_key secret_key를 키 값으로 바꿉니다. 이 예제에서는 임베딩 및 채팅 완성을 위해 OpenAI를 사용하므로 환경 변수에 OpenAI 키도 지정해야 합니다.
import os
# Get keys for your project from the project settings page
# https://cloud.langfuse.com
os.environ["LANGFUSE_PUBLIC_KEY"] = ""
os.environ["LANGFUSE_SECRET_KEY"] = ""
os.environ["LANGFUSE_HOST"] = "https://cloud.langfuse.com" # 🇪🇺 EU region
# os.environ["LANGFUSE_HOST"] = "https://us.cloud.langfuse.com" # 🇺🇸 US region
# Your openai key
os.environ["OPENAI_API_KEY"] = ""
from llama_index.core import Settings
from llama_index.core.callbacks import CallbackManager
from langfuse.llama_index import LlamaIndexCallbackHandler
langfuse_callback_handler = LlamaIndexCallbackHandler()
Settings.callback_manager = CallbackManager([langfuse_callback_handler])
Milvus Lite를 사용한 색인
from llama_index.core import Document
doc1 = Document(text="""
Maxwell "Max" Silverstein, a lauded movie director, screenwriter, and producer, was born on October 25, 1978, in Boston, Massachusetts. A film enthusiast from a young age, his journey began with home movies shot on a Super 8 camera. His passion led him to the University of Southern California (USC), majoring in Film Production. Eventually, he started his career as an assistant director at Paramount Pictures. Silverstein's directorial debut, “Doors Unseen,” a psychological thriller, earned him recognition at the Sundance Film Festival and marked the beginning of a successful directing career.
""")
doc2 = Document(text="""
Throughout his career, Silverstein has been celebrated for his diverse range of filmography and unique narrative technique. He masterfully blends suspense, human emotion, and subtle humor in his storylines. Among his notable works are "Fleeting Echoes," "Halcyon Dusk," and the Academy Award-winning sci-fi epic, "Event Horizon's Brink." His contribution to cinema revolves around examining human nature, the complexity of relationships, and probing reality and perception. Off-camera, he is a dedicated philanthropist living in Los Angeles with his wife and two children.
""")
# Example index construction + LLM query
from llama_index.core import VectorStoreIndex
from llama_index.core import StorageContext
from llama_index.vector_stores.milvus import MilvusVectorStore
vector_store = MilvusVectorStore(
uri="tmp/milvus_demo.db", dim=1536, overwrite=False
)
storage_context = StorageContext.from_defaults(vector_store=vector_store)
index = VectorStoreIndex.from_documents(
[doc1,doc2], storage_context=storage_context
)
쿼리
# Query
response = index.as_query_engine().query("What did he do growing up?")
print(response)
# Chat
response = index.as_chat_engine().chat("What did he do growing up?")
print(response)
Langfuse에서 추적 탐색하기
# As we want to immediately see result in Langfuse, we need to flush the callback handler
langfuse_callback_handler.flush()
완료! 랭퓨즈 프로젝트에서 인덱스와 쿼리의 추적을 확인할 수 있습니다.
트레이스 예시(공개 링크):
Langfuse에서 추적:
Langfuse 추적
고급 기능에 관심이 있으신가요?
전체 통합 문서를 참조하여 고급 기능 및 사용 방법에 대해 자세히 알아보세요:
- Langfuse Python SDK 및 기타 통합과의 상호 운용성
- 트레이스에 사용자 정의 메타데이터 및 속성 추가하기