Skip to content

Import Colab Secrets userdata module.

from google.colab import userdata

os.environ[“OPENAI_API_KEY”] = userdata.get(“OPENAI_API_KEY”)

## Dataset for evaluation
In this example, we will be using the transcripts from MeetingBank dataset [1] as our contextual information.
```python
%%capture
from datasets import load_dataset
meetingbank = load_dataset("huuuyeah/meetingbank")

This function helps extract transcripts and converts them into a list of objects of type llama_index.core.Document.

from llama_index.core import Document
def extract_and_create_documents(transcripts):
documents = []
for transcript in transcripts:
try:
doc = Document(text=transcript)
documents.append(doc)
except Exception as e:
print(f"Failed to create document")
return documents
transcripts = [meeting["transcript"] for meeting in meetingbank["train"]]
documents = extract_and_create_documents(
transcripts[:5]
) ## Using only 5 transcripts to keep this example fast and concise.

Set up an embedding model. We will be using the text-embedding-3-small model here.

from llama_index.embeddings.openai import OpenAIEmbedding
embedding_model = OpenAIEmbedding(
model="text-embedding-3-small", embed_batch_size=100, max_retries=3
)

Split documents into nodes and generate their embeddings

from aimon_llamaindex import generate_embeddings_for_docs
nodes = generate_embeddings_for_docs(documents, embedding_model)

Insert the nodes with embeddings into in-memory Vector Store Index.

from aimon_llamaindex import build_index
index = build_index(nodes)

Instantiate a Vector Index Retrieiver

from aimon_llamaindex import build_retriever
retriever = build_retriever(index, similarity_top_k=5)

Configure the Large Language Model. Here we choose OpenAI’s gpt-4o-mini model with temperature setting of 0.1.

## OpenAI's LLM
from llama_index.llms.openai import OpenAI
llm = OpenAI(
model="gpt-4o-mini",
temperature=0.4,
system_prompt="""
Please be professional and polite.
Answer the user's question in a single line.
Even if the context lacks information to answer the question, make
sure that you answer the user's question based on your own knowledge.
""",
)

Define your query and instructions

user_query = "Which council bills were amended for zoning regulations?"
user_instructions = [
"Keep the response concise, preferably under the 100 word limit."
]

Update the LLM’s system prompt with the user’s instructions defined dynamically

llm.system_prompt += (
f"Please comply to the following instructions {user_instructions}."
)

Retrieve a response for the query.

from aimon_llamaindex import get_response
llm_response = get_response(user_query, retriever, llm)

Configure AIMon Client

from aimon import Client
aimon_client = Client(
auth_header="Bearer {}".format(userdata.get("AIMON_API_KEY"))
)

Using AIMon’s Instruction Adherence Model (a.k.a. Guideline Evaluator)

This model evaluates if generated text adheres to given instructions, ensuring that LLMs follow the user’s guidelines and intent across various tasks for more accurate and relevant outputs.

from aimon_llamaindex.evaluators import GuidelineEvaluator
guideline_evaluator = GuidelineEvaluator(aimon_client)
evaluation_result = guideline_evaluator.evaluate(
user_query, llm_response, user_instructions
)
print(json.dumps(evaluation_result, indent=4))
{
"extractions": [],
"instructions_list": [
{
"explanation": "",
"follow_probability": 0.982,
"instruction": "Keep the response concise, preferably under the 100 word limit.",
"label": true
}
],
"score": 1.0
}

Using AIMon’s Hallucination Detection Evaluator Model (HDM-2)

AIMon’s HDM-2 detects hallucinated content in LLM outputs. It provides a “hallucination score” (0.0–1.0) quantifying the likelihood of factual inaccuracies or fabricated information, ensuring more reliable and accurate responses.

from aimon_llamaindex.evaluators import HallucinationEvaluator
hallucination_evaluator = HallucinationEvaluator(aimon_client)
evalution_result = hallucination_evaluator.evaluate(user_query, llm_response)
## Printing the initial evaluation result for Hallucination
print(json.dumps(evalution_result, indent=4))
{
"is_hallucinated": "False",
"score": 0.22446,
"sentences": [
{
"score": 0.22446,
"text": "The council bills amended for zoning regulations include the small lot moratorium and the text amendment related to off-street parking exemptions for preexisting small lots. These amendments aim to balance the interests of local neighborhoods, health institutions, and developers."
}
]
}

Using AIMon’s Context Relevance Evaluator to evaluate the relevance of context data used by the LLM to generate the response.

from aimon_llamaindex.evaluators import ContextRelevanceEvaluator
evaluator = ContextRelevanceEvaluator(aimon_client)
task_definition = (
"Find the relevance of the context data used to generate this response."
)
evaluation_result = evaluator.evaluate(
user_query, llm_response, task_definition
)
print(json.dumps(evaluation_result, indent=4))
[
{
"explanations": [
"Document 1 discusses a council bill related to zoning regulations, specifically mentioning a text amendment that aims to balance neighborhood interests with developer needs. However, it primarily focuses on parking issues and personal experiences rather than detailing specific zoning regulation amendments or the council bills directly related to them, which makes it less relevant to the query.",
"2. Document 2 mentions zoning and development issues, including the need for mass transit and affordability, but it does not provide specific information on which council bills were amended for zoning regulations. The discussion is more about general concerns regarding development and transportation rather than direct references to zoning amendments.",
"3. Document 3 touches on zoning laws and amendments but does not specify which council bills were amended for zoning regulations. While it discusses the context of zoning and housing, it lacks concrete details that directly answer the query about specific bills.",
"4. Document 4 discusses broader issues about affordable housing and transportation without directly addressing any specific council bills or amendments related to zoning regulations. The focus is on general priorities and funding rather than specific legislative changes, making it less relevant to the query.",
"5. Document 5 mentions support for a zoning code amendment regarding parking exemptions for small lots, which is somewhat related to zoning regulations. However, it does not provide specific details about the council bills amended for zoning regulations, thus failing to fully address the query."
],
"query": "Which council bills were amended for zoning regulations?",
"relevance_scores": [
40.5,
40.25,
44.25,
38.5,
43.0
]
}
]

In this notebook, we built a simple RAG application using the LlamaIndex framework. After retrieving a response to a query, we assessed it with AIMon’s evaluators.

[1]. Y. Hu, T. Ganter, H. Deilamsalehy, F. Dernoncourt, H. Foroosh, and F. Liu, “MeetingBank: A Benchmark Dataset for Meeting Summarization,” arXiv, May 2023. [Online]. Available: https://arxiv.org/abs/2305.17529. Accessed: Jan. 16, 2025.