Langfuse로 RAG 쿼리 추적하기 (Using Langfuse to Trace Queries in RAG)
이 문서는 Langfuse로 RAG에서 쿼리를 추적하는 방법을 보여 주는 간단한 cookbook이에요. RAG 파이프라인은 문서 저장과 검색을 위해 LlamaIndex와 Milvus Lite로 구현돼요.
이 quickstart에서는 Milvus Lite를 벡터 스토어로 사용해 LlamaIndex 애플리케이션을 설정하는 방법을 보여 드려요. 또한 Langfuse LlamaIndex 통합으로 애플리케이션을 추적하는 방법도 보여 드려요.
Langfuse는 팀이 협력해 LLM 애플리케이션을 디버깅, 분석, 반복 개선할 수 있게 돕는 오픈소스 LLM 엔지니어링 플랫폼이에요. 모든 플랫폼 기능은 개발 워크플로우를 가속화하기 위해 네이티브로 통합돼요.
Milvus Lite는 벡터 임베딩과 유사도 검색으로 AI 애플리케이션을 구동하는 오픈소스 벡터 데이터베이스인 Milvus의 경량 버전이에요.
출처: Milvus 문서
본문
설정 (Setup)
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로 인덱싱 (Index using 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)
# 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에서 트레이스 살펴보기 (Explore traces in 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 및 다른 통합과의 상호운용성
- 트레이스에 커스텀 메타데이터와 속성 추가
더 알아보기 (Learn more)
- Langfuse — 오픈소스 LLM 엔지니어링 플랫폼
- Langfuse LlamaIndex 통합 문서 — 통합의 고급 기능
- Milvus Lite — 경량 Milvus