Colab에서 열기
UpTrain [github || website || docs]은 LLM 애플리케이션을 평가하고 개선하기 위한 오픈소스 플랫폼입니다. 20개 이상의 사전 구성된 검사(언어, 코드, embedding 사용 사례 포함)에 대한 등급을 제공하고, 실패 사례에 대한 근본 원인 분석을 수행하며, 이를 해결하기 위한 가이드를 제공합니다.

UpTrain Callback Handler

이 노트북은 UpTrain callback handler가 파이프라인에 원활하게 통합되어 다양한 평가를 용이하게 하는 방법을 보여줍니다. 우리는 chain을 평가하는 데 적합하다고 판단한 몇 가지 평가를 선택했습니다. 이러한 평가는 자동으로 실행되며 결과가 출력에 표시됩니다. UpTrain의 평가에 대한 자세한 내용은 여기에서 확인할 수 있습니다. 시연을 위해 LangChain의 선택된 retriever들이 강조됩니다:

1. Vanilla RAG

RAG는 context를 검색하고 응답을 생성하는 데 중요한 역할을 합니다. 성능과 응답 품질을 보장하기 위해 다음 평가를 수행합니다:
  • Context Relevance: 쿼리에서 추출한 context가 응답과 관련이 있는지 확인합니다.
  • Factual Accuracy: LLM이 환각을 일으키거나 잘못된 정보를 제공하는지 평가합니다.
  • Response Completeness: 응답이 쿼리에서 요청한 모든 정보를 포함하는지 확인합니다.

2. Multi Query Generation

MultiQueryRetriever는 원래 질문과 유사한 의미를 가진 질문의 여러 변형을 생성합니다. 복잡성을 고려하여 이전 평가를 포함하고 다음을 추가합니다:
  • Multi Query Accuracy: 생성된 multi-query들이 원래 쿼리와 동일한 의미를 갖는지 확인합니다.

3. Context Compression and Reranking

Re-ranking은 쿼리와의 관련성을 기반으로 노드를 재정렬하고 상위 n개의 노드를 선택하는 것을 포함합니다. re-ranking이 완료되면 노드 수가 줄어들 수 있으므로 다음 평가를 수행합니다:
  • Context Reranking: 재정렬된 노드의 순서가 원래 순서보다 쿼리와 더 관련이 있는지 확인합니다.
  • Context Conciseness: 줄어든 노드 수가 여전히 필요한 모든 정보를 제공하는지 검사합니다.
이러한 평가는 chain에서 RAG, MultiQueryRetriever 및 Reranking 프로세스의 견고성과 효과를 종합적으로 보장합니다.

Install Dependencies

pip install -qU langchain langchain_openai langchain-community uptrain faiss-cpu flashrank
huggingface/tokenizers: The current process just got forked, after parallelism has already been used. Disabling parallelism to avoid deadlocks...
To disable this warning, you can either:
 - Avoid using `tokenizers` before the fork if possible
 - Explicitly set the environment variable TOKENIZERS_PARALLELISM=(true | false)
WARNING: There was an error checking the latest version of pip.
Note: you may need to restart the kernel to use updated packages.
참고: 라이브러리의 GPU 지원 버전을 사용하려면 faiss-cpu 대신 faiss-gpu를 설치할 수도 있습니다.

Import Libraries

from getpass import getpass

from langchain.chains import RetrievalQA
from langchain.retrievers import ContextualCompressionRetriever
from langchain.retrievers.document_compressors import FlashrankRerank
from langchain.retrievers.multi_query import MultiQueryRetriever
from langchain_community.callbacks.uptrain_callback import UpTrainCallbackHandler
from langchain_community.document_loaders import TextLoader
from langchain_community.vectorstores import FAISS
from langchain_core.output_parsers.string import StrOutputParser
from langchain_core.prompts.chat import ChatPromptTemplate
from langchain_core.runnables.passthrough import RunnablePassthrough
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
from langchain_text_splitters import (
    RecursiveCharacterTextSplitter,
)

Load the documents

loader = TextLoader("../../how_to/state_of_the_union.txt")
documents = loader.load()

Split the document into chunks

text_splitter = RecursiveCharacterTextSplitter(chunk_size=1000, chunk_overlap=0)
chunks = text_splitter.split_documents(documents)

Create the retriever

embeddings = OpenAIEmbeddings()
db = FAISS.from_documents(chunks, embeddings)
retriever = db.as_retriever()

Define the LLM

llm = ChatOpenAI(temperature=0, model="gpt-4")

Setup

UpTrain은 다음을 제공합니다:
  1. 고급 드릴다운 및 필터링 옵션이 있는 대시보드
  2. 실패 사례 간의 인사이트 및 공통 주제
  3. 프로덕션 데이터의 관찰 가능성 및 실시간 모니터링
  4. CI/CD 파이프라인과의 원활한 통합을 통한 회귀 테스트
UpTrain을 사용하여 평가하기 위해 다음 옵션 중에서 선택할 수 있습니다:

1. UpTrain의 Open-Source Software (OSS)

오픈소스 평가 서비스를 사용하여 모델을 평가할 수 있습니다. 이 경우 OpenAI API key를 제공해야 합니다. UpTrain은 GPT 모델을 사용하여 LLM이 생성한 응답을 평가합니다. API key는 여기에서 얻을 수 있습니다. UpTrain 대시보드에서 평가를 보려면 터미널에서 다음 명령을 실행하여 설정해야 합니다:
git clone https://github.com/uptrain-ai/uptrain
cd uptrain
bash run_uptrain.sh
이렇게 하면 로컬 머신에서 UpTrain 대시보드가 시작됩니다. http://localhost:3000/dashboard에서 액세스할 수 있습니다. Parameters:
  • key_type=“openai”
  • api_key=“OPENAI_API_KEY”
  • project_name=“PROJECT_NAME”

2. UpTrain Managed Service and Dashboards

또는 UpTrain의 관리형 서비스를 사용하여 모델을 평가할 수 있습니다. 여기에서 무료 UpTrain 계정을 만들고 무료 평가판 크레딧을 받을 수 있습니다. 더 많은 평가판 크레딧을 원하시면 여기에서 UpTrain 관리자와 통화를 예약하세요. 관리형 서비스를 사용하면 다음과 같은 이점이 있습니다:
  1. 로컬 머신에 UpTrain 대시보드를 설정할 필요가 없습니다.
  2. API key 없이도 많은 LLM에 액세스할 수 있습니다.
평가를 수행한 후 https://dashboard.uptrain.ai/dashboard에서 UpTrain 대시보드에서 확인할 수 있습니다. Parameters:
  • key_type=“uptrain”
  • api_key=“UPTRAIN_API_KEY”
  • project_name=“PROJECT_NAME”
참고: project_name은 수행된 평가가 UpTrain 대시보드에 표시될 프로젝트 이름입니다.

Set the API key

노트북에서 API key를 입력하라는 메시지가 표시됩니다. 아래 셀의 key_type 매개변수를 변경하여 OpenAI API key 또는 UpTrain API key 중에서 선택할 수 있습니다.
KEY_TYPE = "openai"  # or "uptrain"
API_KEY = getpass()

1. Vanilla RAG

UpTrain callback handler는 생성된 쿼리, context 및 응답을 자동으로 캡처하고 응답에 대해 다음 세 가지 평가를 실행합니다 (0에서 1까지 등급 부여):
  • Context Relevance: 쿼리에서 추출한 context가 응답과 관련이 있는지 확인합니다.
  • Factual Accuracy: 응답이 얼마나 사실적으로 정확한지 확인합니다.
  • Response Completeness: 응답이 쿼리에서 요청하는 모든 정보를 포함하는지 확인합니다.
# Create the RAG prompt
template = """Answer the question based only on the following context, which can include text and tables:
{context}
Question: {question}
"""
rag_prompt_text = ChatPromptTemplate.from_template(template)

# Create the chain
chain = (
    {"context": retriever, "question": RunnablePassthrough()}
    | rag_prompt_text
    | llm
    | StrOutputParser()
)

# Create the uptrain callback handler
uptrain_callback = UpTrainCallbackHandler(key_type=KEY_TYPE, api_key=API_KEY)
config = {"callbacks": [uptrain_callback]}

# Invoke the chain with a query
query = "What did the president say about Ketanji Brown Jackson"
docs = chain.invoke(query, config=config)
2024-04-17 17:03:44.969 | INFO     | uptrain.framework.evalllm:evaluate_on_server:378 - Sending evaluation request for rows 0 to <50 to the Uptrain
2024-04-17 17:04:05.809 | INFO     | uptrain.framework.evalllm:evaluate:367 - Local server not running, start the server to log data and visualize in the dashboard!
Question: What did the president say about Ketanji Brown Jackson
Response: The president mentioned that he had nominated Ketanji Brown Jackson to serve on the United States Supreme Court 4 days ago. He described her as one of the nation's top legal minds who will continue Justice Breyer’s legacy of excellence. He also mentioned that she is a former top litigator in private practice, a former federal public defender, and comes from a family of public school educators and police officers. He described her as a consensus builder and noted that since her nomination, she has received a broad range of support from various groups, including the Fraternal Order of Police and former judges appointed by both Democrats and Republicans.

Context Relevance Score: 1.0
Factual Accuracy Score: 1.0
Response Completeness Score: 1.0

2. Multi Query Generation

MultiQueryRetriever는 RAG 파이프라인이 쿼리를 기반으로 최상의 문서 세트를 반환하지 못할 수 있는 문제를 해결하는 데 사용됩니다. 원래 쿼리와 동일한 의미를 가진 여러 쿼리를 생성한 다음 각각에 대한 문서를 가져옵니다. 이 retriever를 평가하기 위해 UpTrain은 다음 평가를 실행합니다:
  • Multi Query Accuracy: 생성된 multi-query들이 원래 쿼리와 동일한 의미를 갖는지 확인합니다.
# Create the retriever
multi_query_retriever = MultiQueryRetriever.from_llm(retriever=retriever, llm=llm)

# Create the uptrain callback
uptrain_callback = UpTrainCallbackHandler(key_type=KEY_TYPE, api_key=API_KEY)
config = {"callbacks": [uptrain_callback]}

# Create the RAG prompt
template = """Answer the question based only on the following context, which can include text and tables:
{context}
Question: {question}
"""
rag_prompt_text = ChatPromptTemplate.from_template(template)

chain = (
    {"context": multi_query_retriever, "question": RunnablePassthrough()}
    | rag_prompt_text
    | llm
    | StrOutputParser()
)

# Invoke the chain with a query
question = "What did the president say about Ketanji Brown Jackson"
docs = chain.invoke(question, config=config)
2024-04-17 17:04:10.675 | INFO     | uptrain.framework.evalllm:evaluate_on_server:378 - Sending evaluation request for rows 0 to <50 to the Uptrain
2024-04-17 17:04:16.804 | INFO     | uptrain.framework.evalllm:evaluate:367 - Local server not running, start the server to log data and visualize in the dashboard!
Question: What did the president say about Ketanji Brown Jackson
Multi Queries:
  - How did the president comment on Ketanji Brown Jackson?
  - What were the president's remarks regarding Ketanji Brown Jackson?
  - What statements has the president made about Ketanji Brown Jackson?

Multi Query Accuracy Score: 0.5
2024-04-17 17:04:22.027 | INFO     | uptrain.framework.evalllm:evaluate_on_server:378 - Sending evaluation request for rows 0 to <50 to the Uptrain
2024-04-17 17:04:44.033 | INFO     | uptrain.framework.evalllm:evaluate:367 - Local server not running, start the server to log data and visualize in the dashboard!
Question: What did the president say about Ketanji Brown Jackson
Response: The president mentioned that he had nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to serve on the United States Supreme Court 4 days ago. He described her as one of the nation's top legal minds who will continue Justice Breyer’s legacy of excellence. He also mentioned that since her nomination, she has received a broad range of support—from the Fraternal Order of Police to former judges appointed by Democrats and Republicans.

Context Relevance Score: 1.0
Factual Accuracy Score: 1.0
Response Completeness Score: 1.0

3. Context Compression and Reranking

reranking 프로세스는 쿼리와의 관련성을 기반으로 노드를 재정렬하고 상위 n개의 노드를 선택하는 것을 포함합니다. reranking이 완료되면 노드 수가 줄어들 수 있으므로 다음 평가를 수행합니다:
  • Context Reranking: 재정렬된 노드의 순서가 원래 순서보다 쿼리와 더 관련이 있는지 확인합니다.
  • Context Conciseness: 줄어든 노드 수가 여전히 필요한 모든 정보를 제공하는지 확인합니다.
# Create the retriever
compressor = FlashrankRerank()
compression_retriever = ContextualCompressionRetriever(
        base_compressor=compressor, base_retriever=retriever
)

# Create the chain
chain = RetrievalQA.from_chain_type(llm=llm, retriever=compression_retriever)

# Create the uptrain callback
uptrain_callback = UpTrainCallbackHandler(key_type=KEY_TYPE, api_key=API_KEY)
config = {"callbacks": [uptrain_callback]}

# Invoke the chain with a query
query = "What did the president say about Ketanji Brown Jackson"
result = chain.invoke(query, config=config)
2024-04-17 17:04:46.462 | INFO     | uptrain.framework.evalllm:evaluate_on_server:378 - Sending evaluation request for rows 0 to <50 to the Uptrain
2024-04-17 17:04:53.561 | INFO     | uptrain.framework.evalllm:evaluate:367 - Local server not running, start the server to log data and visualize in the dashboard!
Question: What did the president say about Ketanji Brown Jackson

Context Conciseness Score: 0.0
Context Reranking Score: 1.0
2024-04-17 17:04:56.947 | INFO     | uptrain.framework.evalllm:evaluate_on_server:378 - Sending evaluation request for rows 0 to <50 to the Uptrain
2024-04-17 17:05:16.551 | INFO     | uptrain.framework.evalllm:evaluate:367 - Local server not running, start the server to log data and visualize in the dashboard!
Question: What did the president say about Ketanji Brown Jackson
Response: The President mentioned that he nominated Circuit Court of Appeals Judge Ketanji Brown Jackson to serve on the United States Supreme Court 4 days ago. He described her as one of the nation's top legal minds who will continue Justice Breyer’s legacy of excellence.

Context Relevance Score: 1.0
Factual Accuracy Score: 1.0
Response Completeness Score: 0.5

UpTrain’s Dashboard and Insights

다음은 대시보드와 인사이트를 보여주는 짧은 비디오입니다: langchain_uptrain.gif
Connect these docs programmatically to Claude, VSCode, and more via MCP for real-time answers.
I