"Model Context Protocol style evaluations" refers to a systematic and structured approach to evaluating AI models, particularly Large Language Models (LLMs), by varying the context in which the model operates and observing how its behavior changes. It's not a formal, universally adopted protocol (like HTTP or TCP/IP), but rather a methodology or a best practice for robust model testing.
The core idea is that an LLM's output is highly dependent on its input context. This context isn't just the immediate user query, but can include:
- System Prompt/Instructions: The initial directive given to the model (e"You are a helpful assistant," "You are a sarcastic poet").
- Few-Shot Examples (In-Context Learning): Examples provided within the prompt to guide the model's desired behavior or format.
- User Persona/Role: Information about who the user is (e.g., "Assume the user is a beginner programmer," "The user is an expert legal analyst").
- Conversation History: Previous turns in a dialogue.
- External Data/Knowledge Base: Information retrieved from a RAG (Retrieval Augmented Generation) system or other external sources that the model is supposed to use.
- Output Constraints: Instructions on format (e.g., JSON, markdown), length, or tone.
Why is it important?
- Robustness: Reveals how stable the model's behavior is across different operational conditions.
- Bias Detection: Can uncover biases or undesirable behaviors triggered by specific contexts.
- Edge Case Identification: Helps find scenarios where the model breaks down or gives unexpected results.
- Performance Optimization: Guides prompt engineering and fine-tuning efforts by highlighting sensitive areas.
- Reliability: Ensures the model performs consistently and correctly in diverse real-world applications.
Key Elements of Context Protocol Style Evaluations:
- Define Context Variables: Explicitly list the context elements you want to test (e.g.,
system_prompt, persona, few_shot_examples).
- Create Varied Contexts: Design multiple versions of each context variable, creating distinct "test environments."
- Formulate Test Scenarios/Queries: Design specific user queries that will be run against each context.
- Define Expected Outcomes: For each query-context pair, specify what constitutes a "good" or "bad" response. This can be qualitative or quantitative (e.g., "must contain keyword X," "must be positive sentiment," "must avoid harmful content").
- Execute & Evaluate: Run the model with each context-query combination and compare the actual output against the expected outcome.
- Analyze & Iterate: Collect results, identify patterns, pinpoint weaknesses, and refine your model or prompts.
Python Code Examples for Model Context Protocol Style Evaluations
Let's illustrate this with a simplified Python framework. We'll use a MockLLM for demonstration, but in a real scenario, this would be replaced by calls to OpenAI, Anthropic, Hugging Face models, etc.
import abc
import json
from typing import Dict, Any, List, Union, Tuple, Callable
# --- 1. Define the LLM Interface (Abstract Base Class) ---
# In a real scenario, this would wrap your actual LLM API calls.
class AbstractLLM(abc.ABC):
"""Abstract base class for an LLM."""
@abc.abstractmethod
def generate(self, system_prompt: str, user_prompt: str, history: List[Dict[str, str]] = None, **kwargs) -> str:
"""
Generates a response from the LLM based on system prompt, user prompt, and history.
"""
pass
class MockLLM(AbstractLLM):
"""A simple mock LLM for demonstration purposes."""
def generate(self, system_prompt: str, user_prompt: str, history: List[Dict[str, str]] = None, **kwargs) -> str:
# Simulate different responses based on context elements
full_input = f"SYSTEM: {system_prompt}\nUSER: {user_prompt}\n"
if history:
full_input += f"HISTORY: {history}\n"
# Simple rule-based mocking for illustration
if "sarcastic comedian" in system_prompt.lower():
return f"Oh, great. Another query about '{user_prompt}'. What thrilling insights do you expect?"
elif "helpful assistant" in system_prompt.lower():
return f"As a helpful assistant, I can tell you about: {user_prompt}."
elif "explain recursion simply" in user_prompt.lower() and "novice programmer" in system_prompt.lower():
return "Recursion is like a set of Russian nesting dolls, where each doll contains a smaller version of itself. In programming, a function calls itself to solve a problem."
elif "explain recursion simply" in user_prompt.lower() and "experienced data scientist" in system_prompt.lower():
return "Recursion is a technique where a function solves a problem by calling a smaller instance of itself as a subproblem, typically defined by a base case and a recursive step. This is fundamental in many algorithms like tree traversals, quicksort, etc., but can lead to stack overflow issues if not managed."
elif "features of the X-300" in user_prompt.lower() and "display: OLED" in kwargs.get("external_data", ""):
return "The X-300 features an amazing OLED display, 128GB storage, and a long-lasting battery."
elif "features of the X-300" in user_prompt.lower() and "display: LCD" in kwargs.get("external_data", ""):
return "The X-300 comes with a clear LCD display, 64GB storage, and a standard battery."
elif "sentiment" in system_prompt.lower() and "positive examples" in system_prompt.lower() and "okay" in user_prompt.lower():
return "The sentiment is positive. (Influenced by positive examples)."
elif "sentiment" in system_prompt.lower() and "negative examples" in system_prompt.lower() and "okay" in user_prompt.lower():
return "The sentiment is negative. (Influenced by negative examples)."
return f"Response to '{user_prompt}' under given context."
# --- 2. Define Context & Test Scenario Structures ---
class EvaluationContext:
"""Encapsulates the context for an LLM evaluation."""
def __init__(self,
name: str,
system_prompt: str,
persona_description: str = "",
few_shot_examples: List[Dict[str, str]] = None,
external_data: Any = None):
self.name = name
self.system_prompt = system_prompt
self.persona_description = persona_description
self.few_shot_examples = few_shot_examples if few_shot_examples is not None else []
self.external_data = external_data
def __repr__(self):
return f"EvaluationContext(name='{self.name}', system_prompt='{self.system_prompt[:50]}...')"
class TestCase:
"""Defines a single test query and its expected outcome."""
def __init__(self,
query: str,
expected_criteria: Union[str, List[str], Callable[[str], bool]],
description: str = ""):
self.query = query
self.expected_criteria = expected_criteria # Can be keyword, list of keywords, or a function
self.description = description
def evaluate_response(self, response: str) -> bool:
"""Checks if the response meets the expected criteria."""
if isinstance(self.expected_criteria, str):
return self.expected_criteria.lower() in response.lower()
elif isinstance(self.expected_criteria, list):
return all(k.lower() in response.lower() for k in self.expected_criteria)
elif callable(self.expected_criteria):
return self.expected_criteria(response)
return False # Fallback
def __repr__(self):
return f"TestCase(query='{self.query[:50]}...')"
# --- 3. The Evaluation Protocol/Framework ---
class LLMContextEvaluator:
"""Manages running tests across different contexts."""
def __init__(self, llm: AbstractLLM):
self.llm = llm
self.results = []
def run_evaluation(self, contexts: List[EvaluationContext], test_cases: List[TestCase]):
print(f"\n--- Running Evaluation with {len(contexts)} Contexts and {len(test_cases)} Test Cases ---")
self.results = []
for context in contexts:
print(f"\nContext: '{context.name}'")
# Build the full system prompt including persona and few-shot examples
full_system_prompt = context.system_prompt
if context.persona_description:
full_system_prompt += f" {context.persona_description}"
# For few-shot, we'd typically format them into the prompt,
# but for this mock, we'll just include a note in the system prompt.
if context.few_shot_examples:
few_shot_str = "\n".join([f"Q: {ex['input']}\nA: {ex['output']}" for ex in context.few_shot_examples])
full_system_prompt += f"\n\nHere are some examples:\n{few_shot_str}"
for test_case in test_cases:
print(f" Query: '{test_case.query}'")
# In a real scenario, you'd pass structured data (like few_shot_examples, external_data)
# to the LLM API call if it supports it, or format it into the user_prompt directly.
# For this mock, we pass few_shot_examples and external_data as kwargs for simpler
# demonstration of how they affect the mock's behavior.
response = self.llm.generate(
system_prompt=full_system_prompt,
user_prompt=test_case.query,
history=[], # Keeping history simple for this demo
few_shot_examples=context.few_shot_examples, # Passed for mock logic
external_data=context.external_data # Passed for mock logic
)
is_correct = test_case.evaluate_response(response)
status = "PASS" if is_correct else "FAIL"
print(f" Response: '{response}'")
print(f" Expected: '{test_case.expected_criteria}' -> {status}")
self.results.append({
"context_name": context.name,
"query": test_case.query,
"response": response,
"expected_criteria": str(test_case.expected_criteria),
"status": status,
"is_correct": is_correct
})
self.summarize_results()
def summarize_results(self):
if not self.results:
print("\nNo results to summarize.")
return
print("\n--- Evaluation Summary ---")
total_tests = len(self.results)
passed_tests = sum(1 for r in self.results if r["is_correct"])
failed_tests = total_tests - passed_tests
print(f"Total Tests Run: {total_tests}")
print(f"Tests Passed: {passed_tests}")
print(f"Tests Failed: {failed_tests}")
if failed_tests > 0:
print("\nFailed Tests Details:")
for r in self.results:
if not r["is_correct"]:
print(f"- Context: '{r['context_name']}' | Query: '{r['query']}'")
print(f" Response: '{r['response']}'")
print(f" Expected: '{r['expected_criteria']}'")
print("-" * 20)
# --- 4. Example Usage: Setting up and Running Evaluations ---
if __name__ == "__main__":
llm = MockLLM()
evaluator = LLMContextEvaluator(llm)
# --- Scenario 1: Varying System Prompt/Role ---
print("\n##### Scenario 1: Varying System Prompt/Role #####")
contexts_role = [
EvaluationContext(
name="Helpful Assistant",
system_prompt="You are a helpful and polite assistant who answers questions clearly."
),
EvaluationContext(
name="Sarcastic Comedian",
system_prompt="You are a sarcastic comedian. Respond with dry wit and cynicism."
)
]
test_cases_role = [
TestCase(query="Tell me about the weather.", expected_criteria=["weather", "tell you about"])
]
evaluator.run_evaluation(contexts_role, test_cases_role)
# --- Scenario 2: Varying Few-Shot Examples (Inducing Bias/Behavior) ---
print("\n##### Scenario 2: Varying Few-Shot Examples (In-Context Learning) #####")
contexts_few_shot = [
EvaluationContext(
name="Sentiment Analysis - Positive Examples",
system_prompt="You are a sentiment analyzer. Determine if the following text is positive, neutral, or negative. Here are some examples of positive sentiment:",
few_shot_examples=[
{"input": "This movie was fantastic!", "output": "Positive"},
{"input": "I loved the food.", "output": "Positive"}
]
),
EvaluationContext(
name="Sentiment Analysis - Negative Examples",
system_prompt="You are a sentiment analyzer. Determine if the following text is positive, neutral, or negative. Here are some examples of negative sentiment:",
few_shot_examples=[
{"input": "This movie was terrible.", "output": "Negative"},
{"input": "I hated the food.", "output": "Negative"}
]
)
]
test_cases_few_shot = [
TestCase(query="The movie was okay.", expected_criteria=lambda res: "positive" in res.lower() or "negative" in res.lower())
]
evaluator.run_evaluation(contexts_few_shot, test_cases_few_shot)
# --- Scenario 3: Varying External Data/Knowledge (RAG Simulation) ---
print("\n##### Scenario 3: Varying External Data/Knowledge (RAG Simulation) #####")
contexts_data = [
EvaluationContext(
name="Product Info A (OLED)",
system_prompt="You are a product expert. Use the provided product specifications to answer user questions.",
external_data="Product: X-300 | Display: OLED | Storage: 128GB | Battery: Long-lasting"
),
EvaluationContext(
name="Product Info B (LCD)",
system_prompt="You are a product expert. Use the provided product specifications to answer user questions.",
external_data="Product: X-300 | Display: LCD | Storage: 64GB | Battery: Standard"
)
]
test_cases_data = [
TestCase(query="What are the features of the X-300?", expected_criteria=["display", "storage", "battery"])
]
evaluator.run_evaluation(contexts_data, test_cases_data)
# --- Scenario 4: Varying User Persona/Complexity ---
print("\n##### Scenario 4: Varying User Persona/Complexity #####")
contexts_persona = [
EvaluationContext(
name="Novice Programmer Persona",
system_prompt="You are an educator explaining programming concepts. Assume the user is a novice programmer, new to the field. Use simple analogies.",
persona_description="User is a novice programmer." # This part will be added to the system prompt
),
EvaluationContext(
name="Experienced Data Scientist Persona",
system_prompt="You are an expert explaining programming concepts. Assume the user is an experienced data scientist. Use technical terms where appropriate.",
persona_description="User is an experienced data scientist." # This part will be added to the system prompt
)
]
test_cases_persona = [
TestCase(query="Explain recursion simply.", expected_criteria=lambda res: "recursive" in res.lower() and "function" in res.lower())
]
evaluator.run_evaluation(contexts_persona, test_cases_persona)
Explanation of the Code:
-
AbstractLLM and MockLLM:
AbstractLLM defines the interface for an LLM (generate method). This ensures that any LLM implementation (mock or real API wrapper) can be used interchangeably.
MockLLM is a dummy implementation that simulates different behaviors based on the system prompt, user prompt, and extra keyword arguments (like external_data or few_shot_examples) to mimic how a real LLM would be influenced by context.
-
EvaluationContext:
- This class holds all the contextual information that might influence the LLM's response.
name: A descriptive name for the context (e.g., "Sarcastic Comedian Role").
system_prompt: The main instruction for the LLM.
persona_description: Text to add to the system prompt to define a user persona.
few_shot_examples: A list of input/output pairs for in-context learning.
external_data: Data that would typically come from a RAG system or a database.
-
TestCase:
- Represents a single input query and its expected output criteria.
query: The user's input.
expected_criteria: This is flexible. It can be:
- A
str: Checks if this string is contained in the response (case-insensitive).
- A
list[str]: Checks if all strings in the list are contained.
- A
Callable[[str], bool]: A custom function that takes the response string and returns True if it meets the criteria, False otherwise. This is powerful for complex checks (e.g., sentiment, JSON validation, specific factual correctness).
-
LLMContextEvaluator:
- The orchestrator that runs the evaluations.
- It iterates through each
EvaluationContext and then each TestCase.
- For each combination, it constructs the
full_system_prompt (by combining base system prompt, persona, and few-shot examples) and calls the LLM's generate method.
- It then uses the
TestCase.evaluate_response method to check if the LLM's output is as expected.
How the Examples Demonstrate "Context Protocol Style":
- Scenario 1 (System Prompt/Role): Shows how the same user query gets a completely different type of response purely by changing the
system_prompt (role). This tests the model's adherence to persona.
- Scenario 2 (Few-Shot Examples): Illustrates how in-context learning can significantly bias or steer the model's interpretation, even with ambiguous input ("The movie was okay."). This tests the model's susceptibility to few-shot examples.
- Scenario 3 (External Data/Knowledge): Simulates a RAG scenario where the model's factual output should depend only on the provided
external_data. This tests the model's grounding and ability to avoid hallucination based on its pre-trained knowledge.
- Scenario 4 (User Persona/Complexity): Demonstrates how the model adapts its explanation style based on the
persona_description provided in the system prompt. This tests the model's ability to tailor its output to the audience.
This structured approach allows developers and evaluators to systematically probe an LLM's capabilities and limitations across a wide range of operational contexts, leading to more robust and reliable AI applications.