라 가 스
빠른 시작
개념
概念 | 含义 |
---|---|
Question | |
Contexts | Retrieved contexts:实际找到的Context |
Answer | 最终生成的答案 |
Ground truths | 参考答案 |
데이터 세 트
from datasets import Dataset
data_samples = {
'question': ['When was the first super bowl?', 'Who won the most super bowls?'],
'answer': ['The first superbowl was held on January 15, 1967', 'The most super bowls have been won by The New England Patriots'],
'contexts' : [['The Super Bowl....season since 1966,','replacing the NFL...in February.'],
['The Green Bay Packers...Green Bay, Wisconsin.','The Packers compete...Football Conference']],
'ground_truth': ['The first superbowl was held on January 15, 1967', 'The New England Patriots have won the Super Bowl a record six times']
}
dataset = Dataset.from_dict(data_samples)
미 터 법
Metric | |||
---|---|---|---|
Context Precision | Retrieval | Question | 是否跑题:检索结果 与 Quesion 是否相关 |
Answer Relevance | Anwser | Question | 是否跑题:生成的答案 是否与 Question 相关 |
Faithfulness | Anwser | Retrieval | 是否参考引用:生成的答案 是否忠诚于 检索结果 |
Context Recall | Retrieval | 参考答案 Ground Truth | 检索的准确性: 检索结果 与 参考答案 是否相关 |
프 롬 프트
컨 텍 스트 정 밀 도
Given question, answer and context verify if the context was useful in arriving at the given answer. Give verdict as "1" if useful and "0" if not with json output.
The output should be a well-formatted JSON instance that conforms to the JSON schema below.
……
Your actual task:
question: 法国的首都是什么?
context: 巴黎是法国的首都。
answer: 巴黎
verification:
답변 관련 성
이 프 롬 프트 는 이해 가 안 된다 .
Generate a question for the given answer and Identify if answer is noncommittal. Give noncommittal as 1 if the answer is noncommittal and 0 if the answer is committal. A noncommittal answer is one that is evasive, vague, or ambiguous. For example, "I don't know" or "I'm not sure" are noncommittal answers
……
Your actual task:
answer: 巴黎
context: 巴黎是法国的首都。
output:
충실 함
Create one or more statements from each sentence in the given answer.
……
Your actual task:
question: 法国的首都是什么?
answer: 巴黎
statements:
Your task is to judge the faithfulness of a series of statements based on a given context. For each statement you must return verdict as 1 if the statement can be verified based on the context or 0 if the statement can not be verified based on the context.
……
Your actual task:
context: 巴黎是法国的首都。
statements: ["\u6cd5\u56fd\u7684\u9996\u90fd\u662f\u5df4\u9ece\u3002"]
answer:
컨 텍 스트 리 콜
Given a context, and an answer, analyze each sentence in the answer and classify if the sentence can be attributed to the given context or not. Use only "Yes" (1) or "No" (0) as a binary classification. Output json with reason.
……
Your actual task:
question: 法国的首都是什么?
context: 巴黎是法国的首都。
answer: 巴黎
classification:
합 성 데이터 생성
동기 : 문서 에서 수 동 으로 수백 개의 Q A (문 제 - 컨 텍 스트 - 답변) 샘플 을 생성 하는 것은 시간이 많이 걸 리고 노력 이 많이 걸릴 수 있습니다 . LL M 을 사용하여 자동 으로 생성 합니다 .
간단한 , ** reason ing , condition ing , 다 중 컨 텍 스트 **
이 범 주 들은 ** evol utions ** 라고 불 립니다 .
생성 할 때 세 가지 범 주의 비율 을 지정 합니다 .
from ragas.testset.generator import TestsetGenerator
from ragas.testset.evolutions import simple, reasoning, multi_context
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
# documents = load your documents
# generator with openai models
generator_llm = ChatOpenAI(model="gpt-3.5-turbo-16k")
critic_llm = ChatOpenAI(model="gpt-4")
embeddings = OpenAIEmbeddings()
generator = TestsetGenerator.from_langchain(
generator_llm,
critic_llm,
embeddings
)
# Change resulting question type distribution
distributions = {
simple: 0.5,
multi_context: 0.4,
reasoning: 0.1
}
# use generator.generate_with_llamaindex_docs if you use llama-index as document loader
testset = generator.generate_with_langchain_docs(documents, 10, distributions)
testset.to_pandas()
데이터를 읽 다
공식 랑 체 인을 사용하고 랑 체 인을 계속 사용하면 문제가 생기 기 쉽지 않습니다 .
자동 언어 적응
평가 하기
평가 프로세 스에 사용 된 Prom pt 를 중국 어로 번역 하여 g pt - 4 - tur bo - pre view 모델을 사용 ; 로 컬 로 캐 시 합니다 .
이제 각 메 트 릭 에 속 하는 프 롬 프트 가 자동 으로 대상 언어 에 적응 됩니다 .
저장 단계는 나중에 재 사 용 하기 위해 기본적으로
. ca cha / rag as
에 저장 합니다 .
# 将Metric中的Prompt翻译成中文
from datasets import Dataset
# from langchain.chat_models import ChatOpenAI
from langchain_openai import ChatOpenAI, OpenAI
from ragas.metrics import (
answer_relevancy,
faithfulness,
context_recall,
context_precision,
answer_correctness,
answer_similarity,
)
from ragas import evaluate
from ragas import adapt
eval_model = ChatOpenAI(model="gpt-3.5-turbo", temperature=0)
# llm used for adaptation
openai_model = ChatOpenAI(model_name="gpt-4-turbo-preview")
# openai_model = OpenAI(model_name="gpt-4-0125-preview", temperature=0)
adapt(
metrics=[
answer_relevancy,
# faithfulness,
context_recall,
context_precision,
answer_correctness,
# answer_similarity,
],
language="Chinese",
llm=openai_model,
)
# Eval
dataset = Dataset.from_dict(
{
"question": ["法国的首都是什么?"],
"contexts": [["巴黎是法国的首都。"]],
"answer": ["巴黎"],
"ground_truths": [["巴黎"]],
}
)
print(dataset)
results = evaluate(dataset, llm=eval_model)
print(results)
생성 된 캐 시 데이터
합 성 데이터 생성
from ragas.testset.generator import TestsetGenerator
from ragas.testset.evolutions import simple, reasoning, multi_context,conditional
from langchain_openai import ChatOpenAI, OpenAIEmbeddings
# generator with openai models
generator_llm = ChatOpenAI(model="gpt-3.5-turbo-16k")
critic_llm = ChatOpenAI(model="gpt-4")
embeddings = OpenAIEmbeddings()
generator = TestsetGenerator.from_langchain(
generator_llm,
critic_llm,
embeddings
)
# adapt to language
language = "Chinese"
generator.adapt(language, evolutions=[simple, reasoning,conditional,multi_context])
generator.save(evolutions=[simple, reasoning, multi_context,conditional])
생성 된 캐 시 데이터
데이터 세 트의 필 드
- 질문 하기
- 컨 텍 스트 : 검색 된 컨 텍 스트
- ground _ truth : 답변 을 참조 하십시오 .
- an wser : 생성 된 답변
- Question: A set of questions.
- Contexts: Retrieved contexts corresponding to each question. This is a
list[list]
since each question can retrieve multiple text chunks. - Answer: Generated answer corresponding to each question.
- Gro und truth s : 각 질문에 해당 하는 Gro und truth s .이것은 각 질문에 대한 예상 되는 답변 에 해당 하는
str
입니다 .
참조 컨 텍 스트 를 사용하지 않았습니다 .
metrics=[
# 这几个都不需要原始的context
context_precision,
answer_relevancy,
faithfulness,
context_recall,
],
B GE 사용
from ragas.llama_index import evaluate
flag_model = HuggingFaceEmbeddings(model_name="BAAI/bge-small-en-v1.5")
query_engine2 = build_query_engine(flag_model)
result = evaluate(query_engine2, metrics, test_questions, test_answers)
통합 Lang Smith
환경 변 수 설정
export LANGCHAIN_TRACING_V2=true
export LANGCHAIN_ENDPOINT=https://api.smith.langchain.com
export LANGCHAIN_API_KEY=<your-api-key>
export LANGCHAIN_PROJECT=<your-project> # if not specified, defaults to "default"
추적 기 만들기
# langsmith
from langchain.callbacks.tracers import LangChainTracer
tracer = LangChainTracer(project_name="callback-experiments")
평가 할 때 사용
from datasets import load_dataset
from ragas.metrics import context_precision
from ragas import evaluate
dataset = load_dataset("explodinggradients/amnesty_qa","english")
evaluate(dataset["train"],metrics=[context_precision],callbacks=[tracer])
L lama In dex 통합
官方文档有问题。