Skip to content

Commit dd6780e

Browse files
committed
Add RAGAS
1 parent 314e2f7 commit dd6780e

File tree

2 files changed

+135
-0
lines changed

2 files changed

+135
-0
lines changed

evals/generate_ragas.py

Lines changed: 125 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,125 @@
1+
import json
2+
import logging
3+
import os
4+
import pathlib
5+
import re
6+
7+
import rich
8+
from azure.identity import AzureDeveloperCliCredential, get_bearer_token_provider
9+
from azure.search.documents import SearchClient
10+
from dotenv_azd import load_azd_env
11+
from langchain_community.document_loaders import JSONLoader
12+
from langchain_core.documents import Document as LCDocument
13+
from langchain_openai import AzureChatOpenAI, AzureOpenAIEmbeddings
14+
from ragas.embeddings import LangchainEmbeddingsWrapper
15+
from ragas.llms import LangchainLLMWrapper
16+
from ragas.testset import TestsetGenerator
17+
from ragas.testset.graph import KnowledgeGraph, Node, NodeType
18+
from ragas.testset.transforms import apply_transforms, default_transforms
19+
20+
logger = logging.getLogger("evals")
21+
22+
load_azd_env()
23+
root_dir = pathlib.Path(__file__).parent.parent
24+
25+
26+
def get_azure_credential():
27+
AZURE_TENANT_ID = os.getenv("AZURE_TENANT_ID")
28+
if AZURE_TENANT_ID:
29+
logger.info("Setting up Azure credential using AzureDeveloperCliCredential with tenant_id %s", AZURE_TENANT_ID)
30+
azure_credential = AzureDeveloperCliCredential(tenant_id=AZURE_TENANT_ID, process_timeout=60)
31+
else:
32+
logger.info("Setting up Azure credential using AzureDeveloperCliCredential for home tenant")
33+
azure_credential = AzureDeveloperCliCredential(process_timeout=60)
34+
return azure_credential
35+
36+
37+
def get_search_documents(azure_credential) -> str:
38+
search_client = SearchClient(
39+
endpoint=f"https://{os.getenv('AZURE_SEARCH_SERVICE')}.search.windows.net",
40+
index_name=os.getenv("AZURE_SEARCH_INDEX"),
41+
credential=azure_credential,
42+
)
43+
search_results = search_client.search(search_text="*", top=10)
44+
return [result for result in search_results]
45+
46+
47+
path = root_dir / "data/Json_Examples/2189.json"
48+
loader = JSONLoader(path, jq_schema=".Description")
49+
docs = loader.load()
50+
51+
52+
azure_credential = get_azure_credential()
53+
azure_openai_api_version = os.getenv("AZURE_OPENAI_API_VERSION") or "2024-06-01"
54+
azure_endpoint = f"https://{os.getenv('AZURE_OPENAI_SERVICE')}.openai.azure.com"
55+
azure_ad_token_provider = get_bearer_token_provider(azure_credential, "https://cognitiveservices.azure.com/.default")
56+
generator_llm = LangchainLLMWrapper(
57+
AzureChatOpenAI(
58+
openai_api_version=azure_openai_api_version,
59+
azure_endpoint=azure_endpoint,
60+
azure_ad_token_provider=azure_ad_token_provider,
61+
azure_deployment=os.getenv("AZURE_OPENAI_EVAL_DEPLOYMENT"),
62+
model=os.environ["AZURE_OPENAI_EVAL_MODEL"],
63+
validate_base_url=False,
64+
)
65+
)
66+
67+
# init the embeddings for answer_relevancy, answer_correctness and answer_similarity
68+
generator_embeddings = LangchainEmbeddingsWrapper(
69+
AzureOpenAIEmbeddings(
70+
openai_api_version=azure_openai_api_version,
71+
azure_endpoint=azure_endpoint,
72+
azure_ad_token_provider=azure_ad_token_provider,
73+
azure_deployment=os.getenv("AZURE_OPENAI_EMB_DEPLOYMENT"),
74+
model=os.environ["AZURE_OPENAI_EMB_MODEL_NAME"],
75+
)
76+
)
77+
78+
# Let's make a knowledge_graph from Azure AI Search documents
79+
search_docs = get_search_documents(azure_credential)
80+
81+
# create the transforms
82+
transforms = default_transforms(
83+
documents=[LCDocument(page_content=doc["content"]) for doc in search_docs],
84+
llm=generator_llm,
85+
embedding_model=generator_embeddings,
86+
)
87+
88+
# convert the documents to Ragas nodes
89+
nodes = []
90+
for doc in search_docs:
91+
content = doc["content"]
92+
citation = doc["sourcepage"]
93+
node = Node(
94+
type=NodeType.DOCUMENT,
95+
properties={
96+
"page_content": f"[[{citation}]]: {content}",
97+
"document_metadata": {"citation": citation},
98+
},
99+
)
100+
nodes.append(node)
101+
102+
kg = KnowledgeGraph(nodes=nodes)
103+
apply_transforms(kg, transforms)
104+
105+
generator = TestsetGenerator(llm=generator_llm, embedding_model=generator_embeddings, knowledge_graph=kg)
106+
dataset = generator.generate(testset_size=10, with_debugging_logs=True)
107+
108+
qa_pairs = []
109+
for sample in dataset.samples:
110+
rich.print(sample)
111+
question = sample.eval_sample.user_input
112+
truth = sample.eval_sample.reference
113+
# Grab the citation in square brackets from the reference_contexts and add it to the truth
114+
citations = []
115+
for context in sample.eval_sample.reference_contexts:
116+
match = re.search(r"\[\[(.*?)\]\]", context)
117+
if match:
118+
citation = match.group(1)
119+
citations.append(f"[{citation}]")
120+
truth += " " + " ".join(citations)
121+
qa_pairs.append({"question": question, "truth": truth})
122+
123+
with open(root_dir / "ground_truth_ragas.jsonl", "a") as f:
124+
for qa_pair in qa_pairs:
125+
f.write(json.dumps(qa_pair) + "\n")

evals/ground_truth_ragas.jsonl

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{"question": "How does Contoso's partnership with Northwind Health benefit employees in terms of balance billing protection, and what role do in-network providers play in this arrangement?", "truth": "Contoso's partnership with Northwind Health benefits employees by offering the Northwind Standard plan, which includes balance billing protection. This protection ensures that employees are not subject to unexpected costs when visiting in-network providers. In-network providers are healthcare providers that have agreed to accept the Northwind Standard plan's payment terms, thereby protecting employees from balance billing. [Northwind_Standard_Benefits_Details.pdf#page=7]"}
2+
{"question": "What Northwind Health do for in-network?", "truth": "In-network providers have agreed to accept the amount of payment offered by Northwind Health, meaning that you pay the portion of the cost that is not covered by the insurance plan. In-network providers may also offer additional services or discounts that are not available to out-of-network providers. [Northwind_Standard_Benefits_Details.pdf#page=8]"}
3+
{"question": "So like, if I go to a doctor not in the Northwind Standard network, how much more do I gotta pay compared to in-network, and are there times when I gotta pay everything myself?", "truth": "If you choose an out-of-network provider under the Northwind Standard plan, you may be responsible for the entire cost of services, or a far greater portion of the cost than you would with an in-network provider. In some cases, Northwind Standard may offer coverage for out-of-network providers, but you may still have to pay more than you would for an in-network provider. [Northwind_Standard_Benefits_Details.pdf#page=10]"}
4+
{"question": "Does Northwind Health cover travel expenses for clinical trial participation?", "truth": "The Northwind Standard plan does not cover travel expenses associated with attending clinical trials. However, Northwind Health can provide information about nearby clinical trials and may be able to help with the cost of travel. [Northwind_Standard_Benefits_Details.pdf#page=24]"}
5+
{"question": "What should I consider when selecting a hospital under the Northwind Standard plan, and how does it affect my out-of-pocket expenses?", "truth": "When selecting a hospital under the Northwind Standard plan, you should consider the services offered by the hospital, such as physical therapy, nutrition counseling, or special programs for specific conditions. Additionally, you should be aware of the cost of care, including any co-pays, coinsurance, or additional charges for services not covered by your plan. Northwind Health may not cover the full cost of a specialist or non-emergency services, so it's important to be aware of these exceptions to manage your out-of-pocket expenses effectively. [Northwind_Standard_Benefits_Details.pdf#page=34]"}
6+
{"question": "How does Northwind Health's balance billing protection benefit participants when selecting in-network hospitals for their healthcare needs?", "truth": "Northwind Health's balance billing protection benefits participants by ensuring they are protected from unexpected costs when visiting in-network providers. This protection means that participants are not billed for the difference between what the provider charges and what the insurance company is willing to pay. By selecting in-network hospitals, participants can avoid balance billing, which can result in significant unexpected expenses. This allows participants to focus on selecting the best hospital for their healthcare needs without worrying about additional financial burdens. [Northwind_Standard_Benefits_Details.pdf#page=34] [Northwind_Standard_Benefits_Details.pdf#page=7]"}
7+
{"question": "What should patients consider about Northwind Health coverage when selecting a hospital and provider?", "truth": "Patients should consider that Northwind Health may not cover the full cost of a specialist or non-emergency services, and they should be aware of any additional costs such as co-pays or coinsurance. It is important to select an in-network hospital and provider, as in-network providers have agreed to accept the payment offered by Northwind Health, potentially offering additional services or discounts. Out-of-network providers may result in higher out-of-pocket costs for patients. [Northwind_Standard_Benefits_Details.pdf#page=34] [Northwind_Standard_Benefits_Details.pdf#page=8]"}
8+
{"question": "How does Northwind Health assist with balance billing protection and what should members consider regarding travel expenses for clinical trials?", "truth": "Northwind Health assists with balance billing protection by offering the Northwind Standard plan, which protects members from unexpected costs when visiting in-network providers. This means that members are not billed for the difference between what a provider charges and what the insurance company pays, as long as they visit in-network providers. However, when it comes to clinical trials, the Northwind Standard plan does not cover travel expenses associated with attending these trials. Members should be aware that they may need to travel to participate in clinical trials, and while Northwind Health can provide information about nearby trials, they may not cover the travel costs. It is important for members to consult with their doctor and understand the costs and benefits before participating in a clinical trial. [Northwind_Standard_Benefits_Details.pdf#page=7] [Northwind_Standard_Benefits_Details.pdf#page=24]"}
9+
{"question": "What are the benefits of choosing in-network providers with Northwind Health?", "truth": "Choosing in-network providers with Northwind Health offers several benefits. Firstly, you are protected from balance billing, which means you won't be billed for the difference between what the provider charges and what your insurance is willing to pay. In-network providers have agreed to accept the payment terms of the Northwind Standard plan, ensuring that you only pay the portion of the cost not covered by the insurance. Additionally, in-network providers may offer additional services or discounts that are not available with out-of-network providers, providing better value for your healthcare expenses. [Northwind_Standard_Benefits_Details.pdf#page=7] [Northwind_Standard_Benefits_Details.pdf#page=8]"}
10+
{"question": "Does Northwind Health cover travel expenses for clinical trials and what should participants consider regarding in-network providers?", "truth": "Northwind Health does not cover travel expenses associated with attending clinical trials under the Northwind Standard plan. Participants should consult with their doctor to ensure clinical trials are suitable for them and be aware of potential costs, as not all trials are free. Additionally, it is important to choose in-network providers whenever possible to minimize out-of-pocket expenses, as out-of-network providers may result in higher costs and lack of additional services or discounts. [Northwind_Standard_Benefits_Details.pdf#page=24] [Northwind_Standard_Benefits_Details.pdf#page=8]"}

0 commit comments

Comments
 (0)