|
| 1 | +import asyncio |
| 2 | +import datetime |
| 3 | + |
| 4 | +from langchain.evaluation.criteria import CriteriaEvalChain |
| 5 | + |
| 6 | +## Using a third party evaluator |
| 7 | +from langchain_aws import BedrockLLM |
| 8 | +from strands import Agent |
| 9 | + |
| 10 | +from strands_evals import Case, Experiment |
| 11 | +from strands_evals.evaluators import Evaluator |
| 12 | +from strands_evals.types import EvaluationData, EvaluationOutput |
| 13 | + |
| 14 | +## Need to install $pip install langchain langchain_aws ## |
| 15 | + |
| 16 | + |
| 17 | +def third_party_example(): |
| 18 | + """ |
| 19 | + Demonstrates integrating a third-party evaluator (LangChain) with the evaluation framework. |
| 20 | +
|
| 21 | + This example: |
| 22 | + 1. Defines a task function that uses an agent to generate responses |
| 23 | + 2. Creates test cases with expected outputs |
| 24 | + 3. Creates a custom evaluator that wraps LangChain's CriteriaEvalChain |
| 25 | + 4. Creates a dataset with the test cases and evaluator |
| 26 | + 5. Runs evaluations and returns the report |
| 27 | +
|
| 28 | + Returns: |
| 29 | + EvaluationReport: The evaluation results |
| 30 | + """ |
| 31 | + |
| 32 | + # 1. Define a task function |
| 33 | + def get_response(case: Case) -> str: |
| 34 | + agent = Agent(callback_handler=None) |
| 35 | + return str(agent(case.input)) |
| 36 | + |
| 37 | + # 2. Create test cases |
| 38 | + test_case1 = Case[str, str]( |
| 39 | + name="knowledge-1", |
| 40 | + input="What is the capital of France?", |
| 41 | + expected_output="The capital of France is Paris.", |
| 42 | + metadata={"category": "knowledge"}, |
| 43 | + ) |
| 44 | + |
| 45 | + test_case2 = Case[str, str]( |
| 46 | + name="knowledge-2", |
| 47 | + input="What color is the ocean?", |
| 48 | + expected_output="The ocean is blue.", |
| 49 | + metadata={"category": "knowledge"}, |
| 50 | + ) |
| 51 | + test_case3 = Case(input="When was World War 2?") |
| 52 | + test_case4 = Case(input="Who was the first president of the United States?") |
| 53 | + |
| 54 | + # 3. Create evaluators |
| 55 | + class LangChainCriteriaEvaluator(Evaluator[str, str]): |
| 56 | + def evaluate(self, evaluation_case: EvaluationData[str, str]) -> EvaluationOutput: |
| 57 | + ## Follow LangChain's Docs: https://python.langchain.com/api_reference/langchain/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html |
| 58 | + # Initialize Bedrock LLM |
| 59 | + bedrock_llm = BedrockLLM( |
| 60 | + model_id="anthropic.claude-v2", # or other Bedrock models |
| 61 | + model_kwargs={ |
| 62 | + "max_tokens_to_sample": 256, |
| 63 | + "temperature": 0.7, |
| 64 | + }, |
| 65 | + ) |
| 66 | + |
| 67 | + criteria = {"correctness": "Is the actual answer correct?", "relevance": "Is the response relevant?"} |
| 68 | + |
| 69 | + evaluator = CriteriaEvalChain.from_llm(llm=bedrock_llm, criteria=criteria) |
| 70 | + |
| 71 | + # Pass in required context for evaluator (look at LangChain's docs) |
| 72 | + result = evaluator.evaluate_strings(prediction=evaluation_case.actual_output, input=evaluation_case.input) |
| 73 | + |
| 74 | + # Make sure to return the correct type |
| 75 | + return EvaluationOutput( |
| 76 | + score=result["score"], test_pass=True if result["score"] > 0.5 else False, reason=result["reasoning"] |
| 77 | + ) |
| 78 | + |
| 79 | + # 4. Create an experiment |
| 80 | + experiment = Experiment[str, str]( |
| 81 | + cases=[test_case1, test_case2, test_case3, test_case4], evaluators=[LangChainCriteriaEvaluator()] |
| 82 | + ) |
| 83 | + |
| 84 | + experiment.to_file("third_party_dataset", "json") |
| 85 | + |
| 86 | + # 5. Run evaluations |
| 87 | + reports = experiment.run_evaluations(get_response) |
| 88 | + return reports[0] |
| 89 | + |
| 90 | + |
| 91 | +async def async_third_party_example(): |
| 92 | + """ |
| 93 | + Demonstrates integrating a third-party evaluator (LangChain) with the evaluation framework asynchronously. |
| 94 | +
|
| 95 | + This example: |
| 96 | + 1. Defines a task function that uses an agent to generate responses |
| 97 | + 2. Creates test cases with expected outputs |
| 98 | + 3. Creates a custom evaluator that wraps LangChain's CriteriaEvalChain |
| 99 | + 4. Creates a dataset with the test cases and evaluator |
| 100 | + 5. Runs evaluations and returns the report |
| 101 | +
|
| 102 | + Returns: |
| 103 | + EvaluationReport: The evaluation results |
| 104 | + """ |
| 105 | + |
| 106 | + # 1. Define a task function |
| 107 | + async def get_response(case: Case) -> str: |
| 108 | + agent = Agent(system_prompt="Be as concise as possible", callback_handler=None) |
| 109 | + response = await agent.invoke_async(case.input) |
| 110 | + return str(response) |
| 111 | + |
| 112 | + # 2. Create test cases |
| 113 | + test_case1 = Case[str, str]( |
| 114 | + name="knowledge-1", |
| 115 | + input="What is the capital of France?", |
| 116 | + expected_output="The capital of France is Paris.", |
| 117 | + metadata={"category": "knowledge"}, |
| 118 | + ) |
| 119 | + |
| 120 | + test_case2 = Case[str, str]( |
| 121 | + name="knowledge-2", |
| 122 | + input="What color is the ocean?", |
| 123 | + expected_output="The ocean is blue.", |
| 124 | + metadata={"category": "knowledge"}, |
| 125 | + ) |
| 126 | + test_case3 = Case(input="When was World War 2?") |
| 127 | + test_case4 = Case(input="Who was the first president of the United States?") |
| 128 | + |
| 129 | + # 3. Create evaluators |
| 130 | + class LangChainCriteriaEvaluator(Evaluator[str, str]): |
| 131 | + def evaluate(self, evaluation_case: EvaluationData[str, str]) -> EvaluationOutput: |
| 132 | + ## Follow LangChain's Docs: https://python.langchain.com/api_reference/langchain/evaluation/langchain.evaluation.criteria.eval_chain.CriteriaEvalChain.html |
| 133 | + # Initialize Bedrock LLM |
| 134 | + bedrock_llm = BedrockLLM( |
| 135 | + model_id="anthropic.claude-v2", # or other Bedrock models |
| 136 | + model_kwargs={ |
| 137 | + "max_tokens_to_sample": 256, |
| 138 | + "temperature": 0.7, |
| 139 | + }, |
| 140 | + ) |
| 141 | + |
| 142 | + criteria = { |
| 143 | + "correctness": "Is the actual answer correct?", |
| 144 | + "relevance": "Is the response relevant?", |
| 145 | + "conciseness": "Is the response short and to the point?", |
| 146 | + } |
| 147 | + |
| 148 | + evaluator = CriteriaEvalChain.from_llm(llm=bedrock_llm, criteria=criteria) |
| 149 | + |
| 150 | + # Pass in required context for evaluator (look at LangChain's docs) |
| 151 | + result = evaluator.evaluate_strings(prediction=evaluation_case.actual_output, input=evaluation_case.input) |
| 152 | + |
| 153 | + # Make sure to return the correct type |
| 154 | + return EvaluationOutput( |
| 155 | + score=result["score"], test_pass=True if result["score"] > 0.5 else False, reason=result["reasoning"] |
| 156 | + ) |
| 157 | + |
| 158 | + async def evaluate_async(self, evaluation_case: EvaluationData[str, str]) -> EvaluationOutput: |
| 159 | + return self.evaluate(evaluation_case) |
| 160 | + |
| 161 | + # 4. Create an experiment |
| 162 | + experiment = Experiment[str, str]( |
| 163 | + cases=[test_case1, test_case2, test_case3, test_case4], evaluators=[LangChainCriteriaEvaluator()] |
| 164 | + ) |
| 165 | + |
| 166 | + # 4.5. (Optional) Save the experiment |
| 167 | + experiment.to_file("async_third_party_dataset") |
| 168 | + |
| 169 | + # 5. Run evaluations |
| 170 | + reports = await experiment.run_evaluations_async(get_response) |
| 171 | + return reports[0] |
| 172 | + |
| 173 | + |
| 174 | +if __name__ == "__main__": |
| 175 | + start = datetime.datetime.now() |
| 176 | + report = asyncio.run(async_third_party_example()) |
| 177 | + end = datetime.datetime.now() |
| 178 | + print("Async: ", end - start) # Async: 0:00:24.050895 |
| 179 | + report.to_file("async_third_party_report") |
| 180 | + report.run_display(include_actual_output=True) |
0 commit comments