Skip to content

Commit 065250c

Browse files
committed
Ground truth generation and evaluation
1 parent 0fa5fca commit 065250c

File tree

5 files changed

+116
-5
lines changed

5 files changed

+116
-5
lines changed

.devcontainer/devcontainer.json

Lines changed: 0 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -46,10 +46,6 @@
4646
"source.fixAll": "explicit"
4747
},
4848
"editor.defaultFormatter": "charliermarsh.ruff"
49-
},
50-
"files.exclude": {
51-
".ruff_cache": true,
52-
".pytest_cache": true
5349
}
5450
}
5551
}

.vscode/settings.json

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -27,5 +27,13 @@
2727
"tests"
2828
],
2929
"python.testing.unittestEnabled": false,
30-
"python.testing.pytestEnabled": true
30+
"python.testing.pytestEnabled": true,
31+
"files.exclude": {
32+
".ruff_cache": true,
33+
".pytest_cache": true,
34+
"__pycache__": true,
35+
"htmlcov": true,
36+
".mypy_cache": true,
37+
".coverage": true
38+
}
3139
}

evals/README.md

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,2 @@
1+
pip install git+https://github.com/Azure-Samples/ai-rag-chat-evaluator/@installable
2+
pip install psycopg2

evals/generate_ground_truth.py

Lines changed: 95 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,95 @@
1+
import logging
2+
import os
3+
from collections.abc import Generator
4+
from pathlib import Path
5+
6+
from azure.identity import DefaultAzureCredential
7+
from dotenv import load_dotenv
8+
from evaltools.gen.generate import generate_test_qa_data
9+
from sqlalchemy import create_engine, select
10+
from sqlalchemy.orm import Session
11+
12+
from fastapi_app.postgres_models import Item
13+
14+
logger = logging.getLogger("ragapp")
15+
16+
17+
def source_retriever() -> Generator[dict, None, None]:
18+
# Connect to the database
19+
DBHOST = os.environ["POSTGRES_HOST"]
20+
DBUSER = os.environ["POSTGRES_USERNAME"]
21+
DBPASS = os.environ["POSTGRES_PASSWORD"]
22+
DBNAME = os.environ["POSTGRES_DATABASE"]
23+
DATABASE_URI = f"postgresql://{DBUSER}:{DBPASS}@{DBHOST}/{DBNAME}"
24+
engine = create_engine(DATABASE_URI, echo=False)
25+
with Session(engine) as session:
26+
# Fetch all products for a particular type
27+
item_types = session.scalars(select(Item.type).distinct())
28+
for item_type in item_types:
29+
records = list(session.scalars(select(Item).filter(Item.type == item_type).order_by(Item.id)))
30+
logger.info(f"Processing database records for type: {item_type}")
31+
yield {
32+
"citations": " ".join([f"[{record.id}] - {record.name}" for record in records]),
33+
"content": "\n\n".join([record.to_str_for_rag() for record in records]),
34+
}
35+
# Fetch each item individually
36+
# records = session.scalars(select(Item).order_by(Item.id))
37+
# for record in records:
38+
# logger.info(f"Processing database record: {record.name}")
39+
# yield {"id": [record.id], "content": record.to_str_for_rag()}
40+
41+
42+
def source_to_text(source) -> str:
43+
return source["content"]
44+
45+
46+
def answer_formatter(answer, source) -> str:
47+
return f"{answer} {source['citations']}"
48+
49+
50+
def get_openai_config_dict() -> dict:
51+
"""Return a dictionary with OpenAI configuration based on environment variables."""
52+
OPENAI_CHAT_HOST = os.getenv("OPENAI_CHAT_HOST")
53+
if OPENAI_CHAT_HOST == "azure":
54+
if api_key := os.getenv("AZURE_OPENAI_KEY"):
55+
logger.info("Using Azure OpenAI Service with API Key from AZURE_OPENAI_KEY")
56+
api_key = os.environ["AZURE_OPENAI_KEY"]
57+
else:
58+
logger.info("Using Azure OpenAI Service with Azure Developer CLI Credential")
59+
azure_credential = DefaultAzureCredential()
60+
api_key = azure_credential.get_token("https://cognitiveservices.azure.com/.default").token
61+
openai_config = {
62+
"api_type": "azure",
63+
"api_base": os.environ["AZURE_OPENAI_ENDPOINT"],
64+
"api_key": api_key,
65+
"api_version": os.environ["AZURE_OPENAI_VERSION"],
66+
"deployment": os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT"],
67+
"model": os.environ["AZURE_OPENAI_CHAT_DEPLOYMENT"],
68+
}
69+
elif OPENAI_CHAT_HOST == "ollama":
70+
raise NotImplementedError("Ollama OpenAI Service is not supported. Switch to Azure or OpenAI.com")
71+
else:
72+
logger.info("Using OpenAI Service with API Key from OPENAICOM_KEY")
73+
openai_config = {
74+
"api_type": "openai",
75+
"api_key": os.environ["OPENAICOM_KEY"],
76+
"model": os.environ["OPENAICOM_CHAT_MODEL"],
77+
"deployment": "none-needed-for-openaicom",
78+
}
79+
return openai_config
80+
81+
82+
if __name__ == "__main__":
83+
logging.basicConfig(level=logging.WARNING)
84+
logger.setLevel(logging.INFO)
85+
load_dotenv(".env", override=True)
86+
87+
generate_test_qa_data(
88+
get_openai_config_dict(),
89+
10,
90+
5,
91+
Path(__file__).parent / "ground_truth.json",
92+
source_retriever,
93+
source_to_text,
94+
answer_formatter,
95+
)

evals/ground_truth.json

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,10 @@
1+
{"question": "What features does the Trailblazer Bike Helmet by Green Equipment offer?", "truth": "The Trailblazer Bike Helmet by Green Equipment offers a lightweight and durable design with an adjustable fit system and ventilation for added comfort. It comes in a vibrant green color and sleek design, suitable for all types of cycling.\n ['[10] - Trailblazer Bike Helmet', '[25] - Stealth Lite Bike Helmet', '[34] - Velocity Red Bike Helmet', '[46] - Zenith Cycling Jersey', '[58] - VelociX 2000 Bike Helmet', '[65] - Sprint PRO Carbon Cycling Helmet', '[76] - Fusion Carbon Cycling Helmet', '[86] - ProVent Bike Helmet', '[95] - AeroLite Cycling Helmet']"}
2+
{"question": "What are the key features of the Daybird Stealth Lite Bike Helmet?", "truth": "The Daybird Stealth Lite Bike Helmet features a sleek matte silver color, lightweight in-mold construction, adjustable retention system, and multiple ventilation channels for optimal airflow. It is designed for cyclists who value safety and style.\n ['[10] - Trailblazer Bike Helmet', '[25] - Stealth Lite Bike Helmet', '[34] - Velocity Red Bike Helmet', '[46] - Zenith Cycling Jersey', '[58] - VelociX 2000 Bike Helmet', '[65] - Sprint PRO Carbon Cycling Helmet', '[76] - Fusion Carbon Cycling Helmet', '[86] - ProVent Bike Helmet', '[95] - AeroLite Cycling Helmet']"}
3+
{"question": "What are the standout features of the Zenith Cycling Jersey by B&R?", "truth": "The Zenith Cycling Jersey by B&R is made from moisture-wicking fabric with a full-length zipper, three rear pockets for storage, and reflective accents for increased visibility in low-light conditions. It is designed for high-performance cycling.\n ['[10] - Trailblazer Bike Helmet', '[25] - Stealth Lite Bike Helmet', '[34] - Velocity Red Bike Helmet', '[46] - Zenith Cycling Jersey', '[58] - VelociX 2000 Bike Helmet', '[65] - Sprint PRO Carbon Cycling Helmet', '[76] - Fusion Carbon Cycling Helmet', '[86] - ProVent Bike Helmet', '[95] - AeroLite Cycling Helmet']"}
4+
{"question": "What are the notable features of the VelociX 2000 Bike Helmet by Raptor Elite?", "truth": "The VelociX 2000 Bike Helmet by Raptor Elite features an aerodynamic design, adjustable fit system, detachable visor, and 14 ventilation channels for optimal airflow. It is suitable for road cycling, mountain biking, and various other cycling activities.\n ['[10] - Trailblazer Bike Helmet', '[25] - Stealth Lite Bike Helmet', '[34] - Velocity Red Bike Helmet', '[46] - Zenith Cycling Jersey', '[58] - VelociX 2000 Bike Helmet', '[65] - Sprint PRO Carbon Cycling Helmet', '[76] - Fusion Carbon Cycling Helmet', '[86] - ProVent Bike Helmet', '[95] - AeroLite Cycling Helmet']"}
5+
{"question": "What features does the Solstix Sprint PRO Carbon Cycling Helmet offer?", "truth": "The Solstix Sprint PRO Carbon Cycling Helmet is crafted from carbon fiber for optimal impact protection and durability. It features an aerodynamic design, adjustable fit system, and ventilation channels for cooling during long rides. The rainbow color with the Solstix emblem adds a stylish touch to the helmet. ['[10] - Trailblazer Bike Helmet', '[25] - Stealth Lite Bike Helmet', '[34] - Velocity Red Bike Helmet', '[46] - Zenith Cycling Jersey', '[58] - VelociX 2000 Bike Helmet', '[65] - Sprint PRO Carbon Cycling Helmet', '[76] - Fusion Carbon Cycling Helmet', '[86] - ProVent Bike Helmet', '[95] - AeroLite Cycling Helmet']"}
6+
{"question": "What features do the Alpine Fusion Goggles offer for skiing?", "truth": "The Alpine Fusion Goggles from WildRunner offer full UV protection and anti-fog lenses to keep vision clear on the slopes. They have a stylish silver frame and orange lenses for a standout look, with adjustable straps for a secure fit and soft foam padding for all-day comfort. ['[3] - Alpine Fusion Goggles', '[5] - Blizzard Rider Snowboard', '[12] - Powder Pro Snowboard', '[16] - Expedition 2022 Goggles', '[22] - Venture 2022 Snowboard', '[30] - Zero Gravity Ski Goggles', '[32] - Cosmic Purple Snowboard', '[39] - Midnight Blue Goggles', '[42] - Gravity 5000 All-Mountain Skis', '[43] - Glacier Frost Snowboard', '[53] - Raven Swift Snowboard', '[60] - SummitRider Snowboard Boots', '[62] - Shadow Black Snowboard', '[72] - GravityZone All-Mountain Skis', '[73] - Omni-Snow Dual Snowboard', '[82] - Maverick Pro Ski Goggles', '[83] - Blizzard Freestyle Snowboard', '[92] - Blizzard Snowboard']"}
7+
{"question": "What is the price and brand of the Blizzard Rider Snowboard?", "truth": "The price of the Blizzard Rider Snowboard by B&R is 299.99. The brand of this versatile snowboard is B&R. ['[3] - Alpine Fusion Goggles', '[5] - Blizzard Rider Snowboard', '[12] - Powder Pro Snowboard', '[16] - Expedition 2022 Goggles', '[22] - Venture 2022 Snowboard', '[30] - Zero Gravity Ski Goggles', '[32] - Cosmic Purple Snowboard', '[39] - Midnight Blue Goggles', '[42] - Gravity 5000 All-Mountain Skis', '[43] - Glacier Frost Snowboard', '[53] - Raven Swift Snowboard', '[60] - SummitRider Snowboard Boots', '[62] - Shadow Black Snowboard', '[72] - GravityZone All-Mountain Skis', '[73] - Omni-Snow Dual Snowboard', '[82] - Maverick Pro Ski Goggles', '[83] - Blizzard Freestyle Snowboard', '[92] - Blizzard Snowboard']"}
8+
{"question": "What are the key features of the Powder Pro Snowboard by Zephyr?", "truth": "The Powder Pro Snowboard by Zephyr is designed for deep snow with floating camber for effortless turns and carbon fiber construction for control at high speeds. It comes in a vibrant turquoise color and is priced at 399.0. ['[3] - Alpine Fusion Goggles', '[5] - Blizzard Rider Snowboard', '[12] - Powder Pro Snowboard', '[16] - Expedition 2022 Goggles', '[22] - Venture 2022 Snowboard', '[30] - Zero Gravity Ski Goggles', '[32] - Cosmic Purple Snowboard', '[39] - Midnight Blue Goggles', '[42] - Gravity 5000 All-Mountain Skis', '[43] - Glacier Frost Snowboard', '[53] - Raven Swift Snowboard', '[60] - SummitRider Snowboard Boots', '[62] - Shadow Black Snowboard', '[72] - GravityZone All-Mountain Skis', '[73] - Omni-Snow Dual Snowboard', '[82] - Maverick Pro Ski Goggles', '[83] - Blizzard Freestyle Snowboard', '[92] - Blizzard Snowboard']"}
9+
{"question": "Describe the features of the Zero Gravity Ski Goggles by Gravitator.", "truth": "The Gravitator Zero Gravity Ski Goggles offer style, performance, and comfort with a sleek white frame, red mirrored lenses, anti-fog coating, and 100% UV protection. They have an adjustable strap for a secure fit and are priced at 79.99. ['[3] - Alpine Fusion Goggles', '[5] - Blizzard Rider Snowboard', '[12] - Powder Pro Snowboard', '[16] - Expedition 2022 Goggles', '[22] - Venture 2022 Snowboard', '[30] - Zero Gravity Ski Goggles', '[32] - Cosmic Purple Snowboard', '[39] - Midnight Blue Goggles', '[42] - Gravity 5000 All-Mountain Skis', '[43] - Glacier Frost Snowboard', '[53] - Raven Swift Snowboard', '[60] - SummitRider Snowboard Boots', '[62] - Shadow Black Snowboard', '[72] - GravityZone All-Mountain Skis', '[73] - Omni-Snow Dual Snowboard', '[82] - Maverick Pro Ski Goggles', '[83] - Blizzard Freestyle Snowboard', '[92] - Blizzard Snowboard']"}
10+
{"question": "What are the standout features of the Gravity 5000 All-Mountain Skis by Gravitator?", "truth": "The Gravity 5000 All-Mountain Skis by Gravitator excel in all conditions with a lightweight wood core, carbon inserts for responsiveness, and ABS sidewalls for durability. They come in a striking blue color and are priced at 699.0. ['[3] - Alpine Fusion Goggles', '[5] - Blizzard Rider Snowboard', '[12] - Powder Pro Snowboard', '[16] - Expedition 2022 Goggles', '[22] - Venture 2022 Snowboard', '[30] - Zero Gravity Ski Goggles', '[32] - Cosmic Purple Snowboard', '[39] - Midnight Blue Goggles', '[42] - Gravity 5000 All-Mountain Skis', '[43] - Glacier Frost Snowboard', '[53] - Raven Swift Snowboard', '[60] - SummitRider Snowboard Boots', '[62] - Shadow Black Snowboard', '[72] - GravityZone All-Mountain Skis', '[73] - Omni-Snow Dual Snowboard', '[82] - Maverick Pro Ski Goggles', '[83] - Blizzard Freestyle Snowboard', '[92] - Blizzard Snowboard']"}

0 commit comments

Comments
 (0)