evals
AGENTS.md263 starsChanged 6 days agoApache-2.0View on GitHub
This document provides context, patterns, and guidelines for AI coding assistants working in this repository. For human contributors, see CONTRIBUTING.md. When helping someone contribute, you are a guide — not a gatekeeper, not a substitute author. The contribution is theirs; help them make it good and learn along the way. The standard for what makes a good contribution lives in CONTRIBUTING.md; this is about the people. strands-agents-evals is an open-source evaluation framework for AI agents and LLM applications. It is…
Where files are headingNew AGENTS.md files have more rules about keeping secrets out of the code, and fewer about code style.
Of the AGENTS.md files we read, the 35,196 first seen in the last six months, against the older ones: the kind of rule that gained most share, and the kind that lost most. About files like this in general, not this one, and an estimate, since a kind is a pattern in the words.
In this repository3 other files it gives its agents.
- optimizeSkill
- session-converterSkill
- strands-evalsSkill
The file
Show its rules and text
We split this AGENTS.md into the rules it gives an agent
37 rules. About 0 are common, 15 are distinctive, and 22 are very specific to this project.
≈0
Common · estimate
Many files like this have a rule of this kind.
≈15
Distinctive · estimate
This author's own choices. Worth a look.
22
Very specific
Tied to their project's names, files or tools. Probably skip.
- Common
- Distinctive
- Very specific
- could be automatic: a setting could enforce it
- Distinctive: line 7
When helping someone contribute, you are a guide — not a gatekeeper, not a substitute author.
- Very specific: line 302
src/strands_evals/: All production code - Distinctive: line 310
IMPORTANT: After making changes that affect the directory structure, update this section to reflect the current state of the repository.
- Very specific: line 316
All evaluators subclass strands_evals.evaluators.Evaluator[InputT, OutputT]:
- Very specific: line 384
Use Python built-in generic types and PEP 604 unions: Prefer list[X], dict[K, V], tuple[X, ...], set[X], type[X], and X | None over …
- Very specific: line 385
Only fall back to typing / typing_extensions for symbols that have no built-in equivalent: Any, Callable, Iterable, Sequence, Mapping, …
- Very specific: line 390
Use Google-style docstrings for public functions, classes, and modules.
- Very specific: line 400
Use %s string interpolation, not f-strings (logging performance).
- Very specific: line 413
No unnecessary dynamic imports: Do not move an import inside a function or guard it with try/except ImportError unless one of the following …
- Very specific: line 420
When a lazy import is justified, leave a one-line comment naming the reason (e.g.
- Distinctive: line 432
Do not swallow exceptions silently.
- Very specific: line 442
Use pytest-asyncio (asyncio_mode = "auto") for async tests.
- Distinctive: line 446
Use real model providers and trace backends.
- Distinctive: line 496
Don't pad the change: No drive-by reformatting, no unrelated refactors, no speculative abstractions or "while I'm here" cleanups.
- Distinctive: line 503
Run the full readiness check: before opening the PR:
- Distinctive: line 507
Don't open a PR with known lint, type, or test failures.
- Distinctive: line 519
Use explicit return types for all functions.
- Very specific: line 520
Use built-in generics (list, dict, tuple, set, type) and PEP 604 unions (X | None, A | B) in annotations.
- Distinctive: line 521
Write Google-style docstrings for public APIs.
- Distinctive: line 522
Use structured logging format.
- Very specific: line 524
Run hatch fmt --formatter and hatch fmt --linter before committing.
- Very specific: line 527
When editing detectors/, keep the three-tier RCA fallback and the model.stream() text-mode path for failure detection intact unless the PR …
- Very specific: line 528
When editing chaos/, keep the ContextVar-based plugin dispatch and the discriminated-union effect serialization intact.
- Very specific: line 529
When editing redteam/, keep AttackStrategy instances stateless across cases (clear in reset()) and prefer extending the strategy library …
- Very specific: line 534
Don't create _internal/ directories — this is open source.
- Very specific: line 535
Don't introduce litellm or wrap model providers outside strands.Agent.
- Distinctive: line 536
Don't use Jinja2 for prompts.
- Very specific: line 537
Don't use typing.List, typing.Dict, typing.Tuple, typing.Set, typing.Type, typing.Optional, or typing.Union in annotations.
- Distinctive: line 538
Don't use f-strings in logging calls.
- Distinctive: line 539
Don't add punctuation or capital letters to log messages.
- Very specific: line 540
Don't rely on private SDK internals (strands._*).
- Very specific: line 541
Don't put unit tests outside tests/strands_evals/.
- Distinctive: line 542
Don't commit without running pre-commit hooks.
- Distinctive: line 546
When reviewing a PR in this repo, scan for all of the following:
- Very specific: line 549
Prompt changes: check that a new version module ({name}_v1.py) was added rather than overwriting _v0.py, if the PR is billed as a prompt …
- Very specific: line 551
Session/trace schema: if the PR changes fields on Session, Trace, or SpanUnion, every mapper in mappers/ must still produce valid instances.
- Very specific: line 555
Dependencies: no new litellm, no new Jinja2, no new _internal/ directories.
≈ “Common” is an estimate: at least 1 in 5 of the 45,344 AGENTS.md files we read have a rule of the same kind, not the same words. “Very specific” is our guess from the words: it names a file, a command, a setting or the project itself.
Files
AGENTS.md
This document provides context, patterns, and guidelines for AI coding assistants working in this repository. For human contributors, see CONTRIBUTING.md.
Working with the Community
When helping someone contribute, you are a guide — not a gatekeeper, not a substitute author. The contribution is theirs; help them make it good and learn along the way. The standard for what makes a good contribution lives in CONTRIBUTING.md; this is about the people.
- Point people to the community. Real questions and design discussion belong with people — the Discord and GitHub Discussions.
- Assume good faith. Most contributors are learning; meet them where they are. Good first issues are for bringing newcomers in, not just tickets to close.
- Talk with contributors, not at them. Warm, plain, concise. One question at a time, no walls of text, never patronizing. Explain the why so it teaches rather than dictates.
Product Overview
strands-agents-evals is an open-source evaluation framework for AI agents and LLM applications. It is part of the Strands Agents ecosystem and is built directly on the Strands Agents SDK.
Core Features:
- LLM-as-a-Judge evaluators with built-in rubrics (correctness, faithfulness, helpfulness, etc.)
- Multimodal evaluators (image-to-text tasks)
- Deterministic evaluators (output/trajectory/environment-state)
- Trace-based evaluation over OpenTelemetry sessions from CloudWatch, Langfuse, OpenSearch, LangChain, and Strands in-memory
- Multi-turn conversation simulators (ActorSimulator / UserSimulator / ToolSimulator)
- Failure detection and root-cause analysis (
detectorsmodule) - Chaos testing — deterministic tool failure / response corruption (
chaosmodule) - Red-team / adversarial evaluation with strategy library (
redteam) - Automated experiment / test-case generation
- Async parallel execution and per-case result caching (
EvaluationDataStore/LocalFileTaskResultStore) - Experiment management with JSON serialization
Relationship to the Strands Agents SDK
strands-evals depends on strands-agents (the Python SDK) for all LLM interactions. Any change in this repo that touches model calls, tools, sessions, traces, hooks, or structured output should be interpreted against the SDK's public API.
- SDK source (external, not in this repo):
strands-agents/sdk-pythonundersrc/strands/ - Key SDK surfaces actually imported by this repo (grep-verified):
strands.Agent, called asAgent(model=..., system_prompt=..., callback_handler=None)and invoked viaagent(prompt, structured_output_model=PydanticModel)strands.models.model.Modeland provider classesstrands.agent.agent_result.AgentResult,strands.context_manager(Offload,ContextState;InteractionsEvaluatorand Reflection passcontext_manager=, never a conversation manager)strands.tools.decorator(DecoratedFunctionTool,FunctionToolMetadata) and the@tooldecorator fromstrandsstrands.types.content.Messagestrands.types.exceptions(EventLoopException,ModelThrottledException)strands.Skill(public, exported instrands.__all__fromstrands.vended_plugins.skills.skill), used by the skill extractors to readSKILL.mdfrontmatterstrands.decisions(DecisionModel,DecisionResult,Question,Uncertain), used byTypedRubricEvaluator(and through itCascade); it reads the per-questionprobabilitiesinDecisionResult.metadata
- Not used as SDK imports (do not add to the list without verifying a real import):
strands.types.traces— this repo defines its ownstrands_evals.types.tracefor session/span modeling; the SDK's trace types are not imported.strands.telemetry— the evals repo has its ownstrands_evals.telemetrymodule. The only reference tostrands.telemetryis the literal string"strands.telemetry.tracer"used as an OpenTelemetry scope name inmappers/constants.py.
Review guidance: When reviewing a PR in this repo, if the change uses any SDK feature (agents, tools, models, streaming, structured output, sessions, hooks, telemetry), verify the usage matches the current SDK public API. If the SDK source is available locally (e.g., via a sibling checkout), scan it; otherwise rely on the imported symbols and docstrings. Flag usages that depend on private SDK internals (anything under _* modules) or deprecated experimental surfaces.
Directory Structure
strands-evals/
│
├── .agents/skills/ # Agent skills
│ ├── optimize/ # Tune a strands-harness agent with `strands-evals optimize`
│ │ └── SKILL.md # Set up, review, run and report an optimize run
│ ├── session-converter/ # Convert agent sessions into experiments
│ │ ├── SKILL.md # Locate sessions, extract episodes, write an experiment
│ │ ├── assets/segmenter.md # Subagent steps: split sessions into episodes
│ │ └── scripts/synthesize_cases.py # Append synthetic cases in the existing cases' voice
│ └── strands-evals/ # Author evaluations with strands-evals
│ └── SKILL.md # Evaluation authoring guidance
│
├── src/strands_evals/ # Main package source code
│ ├── __init__.py # Public API exports
│ ├── case.py # Case[InputT, OutputT] test scenario
│ ├── experiment.py # Experiment orchestration + run_evaluations
│ ├── eval_task_handler.py # EvalTaskHandler, TracedHandler, @eval_task
│ ├── evaluation_data_store.py # EvaluationDataStore
│ ├── local_file_task_result_store.py # LocalFileTaskResultStore
│ ├── _async.py # Async helpers
│ ├── utils.py # Shared utilities
│ │
│ ├── evaluators/ # Evaluator implementations
│ │ ├── evaluator.py # Base Evaluator[InputT, OutputT]
│ │ ├── cascade.py # Cascade: typed rubric first, fallback evaluator for uncertain cases
│ │ ├── coherence_evaluator.py
│ │ ├── conciseness_evaluator.py
│ │ ├── correctness_evaluator.py
│ │ ├── faithfulness_evaluator.py
│ │ ├── goal_success_rate_evaluator.py
│ │ ├── harmfulness_evaluator.py
│ │ ├── helpfulness_evaluator.py
│ │ ├── instruction_following_evaluator.py
│ │ ├── interactions_evaluator.py
│ │ ├── output_evaluator.py
│ │ ├── refusal_evaluator.py
│ │ ├── response_relevance_evaluator.py
│ │ ├── stereotyping_evaluator.py
│ │ ├── tool_parameter_accuracy_evaluator.py
│ │ ├── tool_selection_accuracy_evaluator.py
│ │ ├── trajectory_evaluator.py
│ │ ├── typed_rubric_evaluator.py # TypedRubricEvaluator (DecisionModel-backed) + scoring formulas
│ │ ├── multimodal_*.py # Multimodal evaluators (MLLM-as-a-Judge)
│ │ ├── chaos/ # Chaos-aware evaluators
│ │ │ ├── failure_communication_evaluator.py
│ │ │ ├── partial_completion_evaluator.py
│ │ │ └── recovery_strategy_evaluator.py
│ │ ├── redteam/ # Red team evaluators
│ │ │ ├── attack_success_evaluator.py # AttackSuccessEvaluator
│ │ │ └── prompt_templates/attack_success/
│ │ ├── deterministic/ # Non-LLM evaluators
│ │ │ ├── output.py
│ │ │ ├── trajectory.py
│ │ │ ├── environment_state.py
│ │ │ └── structured_output.py # StructuredOutputSimilarity + StructuredOutputReport (stickler extra)
│ │ └── prompt_templates/ # Per-evaluator prompt modules
│ │ └── {evaluator_name}/{name}_v0.py # Exports SYSTEM_PROMPT constant
│ │
│ ├── chaos/ # Deterministic fault injection (Strands Plugin hooks)
│ │ ├── case.py # ChaosCase + ChaosCase.expand
│ │ ├── effects.py # Timeout / NetworkError / ExecutionError /
│ │ │ # ValidationError / TruncateFields /
│ │ │ # RemoveFields / CorruptValues
│ │ ├── experiment.py # ChaosExperiment (sets active case via ContextVar)
│ │ ├── plugin.py # ChaosPlugin (tool + model hooks via ContextVar)
│ │ └── _context.py # ContextVar holding the active ChaosCase
│ │
│ ├── redteam/ # Adversarial / red-team evaluation
│ │ ├── README.md # Module quick-start + walkthrough
│ │ ├── case.py # RedTeamCase + RedTeamConfig
│ │ ├── experiment.py # RedTeamExperiment (case × strategy cross-product)
│ │ ├── task.py # _build_attacker_task
│ │ ├── utils.py # _put_model_field (used by to_dict)
│ │ ├── report.py # RedTeamReport / AttackResult / GroupedSummary
│ │ ├── generators/ # AdversarialCaseGenerator + TargetSpec
│ │ ├── strategies/ # AttackStrategy base + per-strategy subpackages
│ │ │ ├── base.py # AttackStrategy ABC + AttackRunResult; MAX_ALLOWED_TURNS = 50 (hard cap)
│ │ │ ├── _common.py # Shared helpers
│ │ │ ├── target_session.py # TargetSession Protocol + StrandsAgentSession,
│ │ │ │ # StrandsMultiAgentSession, TargetCheckpoint, ToolUseEntry,
│ │ │ │ # as_target_session
│ │ │ ├── bad_likert_judge/ # BadLikertJudgeStrategy
│ │ │ ├── crescendo/ # CrescendoStrategy + crescendo_v0 prompt
│ │ │ ├── goat/ # GoatStrategy + goat_v0 prompt
│ │ │ ├── pair/ # PairStrategy + prompt template
│ │ │ ├── prompt_strategy/ # PromptStrategy + gradual_escalation template
│ │ │ └── sequentialbreak/ # SequentialBreakStrategy
│ │ └── (evaluator in evaluators/redteam/, types in types/redteam/)
│ │
│ ├── optimization/ # Optimizer: searches declared agent changes, picks one on validation
│ │ ├── declaration/ # Markers, tunable / TunableFactory, Space (flat typed keys), files, tools
│ │ ├── candidate.py # Candidate (typed values, content id, parent), diff
│ │ ├── execution/ # Trial statuses, default rollout, trace capture, TrialRunner
│ │ ├── scoring/ # Metric registry, objectives (incl. Pareto), constraints
│ │ ├── score_model/ # ScoreModel / Fit protocols, BayesBenchModel, effects, the ranking
│ │ ├── bayesbench/ # Factor encoder, conjugate posterior, prior-scale averaging, contrasts, held-out
│ │ │ # diagnostics; numpy/scipy only, imported only by score_model/bayesbench.py
│ │ ├── search/ # Proposer, Block / Search / schedules, TPE, Reflection, Thompson
│ │ ├── selection/ # Selection, TopRanked (picks the parent)
│ │ ├── setup/ # Split, Budget
│ │ ├── end_phase.py # FinalPick: finalists on validation, champion (and Pareto front) vs baseline on test
│ │ ├── record/ # Run directory, events.jsonl, resume
│ │ ├── optimizer.py / result.py
│ │ ├── prompt_templates/reflection/
│ │ └── (data records in types/optimization/)
│ │
│ ├── experimental/ # Experimental features (no stability guarantees)
│ │ └── context_utilization_evaluator.py # Useful / gathered tokens over a Session
│ │ # (prompt in evaluators/prompt_templates/)
│ │
│ ├── detectors/ # Failure detection + RCA
│ │ ├── failure_detector.py # detect_failures (model.stream text mode)
│ │ ├── root_cause_analyzer.py # analyze_root_cause (Agent + structured output)
│ │ ├── diagnosis.py # diagnose_session pipeline
│ │ ├── chunking.py # Context-overflow fallback
│ │ ├── utils.py # _resolve_model, _serialize_session, etc.
│ │ ├── constants.py
│ │ └── prompt_templates/
│ │ ├── failure_detection/
│ │ └── root_cause/ # root_cause_v0 + root_cause_merge_v0
│ │
│ ├── simulation/ # Multi-turn simulators
│ │ ├── actor_simulator.py # ActorSimulator (acts as user)
│ │ ├── tool_simulator.py # ToolSimulator (LLM-powered tool responses)
│ │ ├── profiles/actor_profile.py
│ │ ├── tools/goal_completion.py
│ │ └── prompt_templates/
│ │
│ ├── generators/ # Test-case/experiment generation
│ │ ├── experiment_generator.py
│ │ ├── topic_planner.py
│ │ └── prompt_template/prompt_templates.py
│ │
│ ├── extractors/ # Extract trajectories from sessions
│ │ ├── trace_extractor.py
│ │ ├── tools_use_extractor.py
│ │ ├── graph_extractor.py
│ │ └── swarm_extractor.py
│ │
│ ├── mappers/ # Session providers -> Session type
│ │ ├── session_mapper.py # Base interface
│ │ ├── cloudwatch_session_mapper.py
│ │ ├── cloudwatch_parser.py
│ │ ├── langchain_otel_session_mapper.py
│ │ ├── openinference_session_mapper.py
│ │ ├── opensearch_session_mapper.py
│ │ └── strands_in_memory_session_mapper.py
│ │
│ ├── providers/ # External trace providers
│ │ ├── trace_provider.py # Base interface
│ │ ├── cloudwatch_provider.py
│ │ ├── langfuse_provider.py
│ │ ├── opensearch_provider.py
│ │ └── exceptions.py
│ │
│ ├── telemetry/ # OpenTelemetry integration
│ │ ├── tracer.py # get_tracer
│ │ ├── config.py # StrandsEvalsTelemetry
│ │ └── _cloudwatch_logger.py
│ │
│ ├── display/
│ │ └── display_console.py # Rich console rendering for reports
│ │
│ ├── tools/
│ │ └── evaluation_tools.py # Helpers used by evaluators
│ │
│ ├── cli/ # `strands-evals` console script
│ │ ├── __main__.py # `python -m strands_evals.cli` entry
│ │ ├── main.py # argparse dispatch
│ │ ├── _common.py # exit codes, format/verbosity, run_command
│ │ ├── _entrypoint.py # `module:attr` resolver + classifier
│ │ ├── _agent_task.py # synthesize_task_function (baggage-tagged)
│ │ ├── _io.py # stdin/stdout/file helpers
│ │ ├── _optimize.py # `optimize`: flags -> Optimizer, cli.json, the .toml run file
│ │ ├── _harness.py # `optimize --config`: a strands-harness portable config as the agent
│ │ ├── _ui_server.py # loopback HTTP server behind `ui`: token and Host rules, routes, guarded writes
│ │ ├── _ui_discovery.py # what `ui` finds in a folder and how it pairs it
│ │ ├── _ui_evaluators.py # the evaluator catalogue the `ui` editor offers
│ │ ├── _ui_markdown.py # the Markdown of a report, experiment or session, which nothing else writes
│ │ ├── assets/ # the `ui` page; no build step, inlined into one document when served
│ │ │ ├── ui.html # markup
│ │ │ ├── ui.css # Strands theme tokens and components
│ │ │ └── ui-*.js # one classic script per concern, loaded in the order ui.html lists
│ │ └── commands/ # subcommand implementations
│ │ ├── run.py
│ │ ├── validate.py
│ │ ├── report.py
│ │ ├── diagnose.py
│ │ ├── generate.py
│ │ ├── fetch.py # pull Session JSON from a TraceProvider
│ │ ├── optimize.py # `optimize run` / `optimize resume`
│ │ └── ui.py # browse and edit experiments, reports and optimizer runs
│ │
│ ├── __main__.py # `python -m strands_evals` shim → cli.main
│ │
│ └── types/ # Public type definitions
│ ├── evaluation.py # EvaluationData / EvaluationOutput
│ ├── evaluation_report.py
│ ├── trace.py # Session, Trace, SpanUnion
│ ├── detector.py # FailureItem, RCAItem, DiagnosisResult, ...
│ ├── multimodal.py
│ ├── typed_rubric.py # Noul / Scale / Choice rubric question types (pydantic dataclasses)
│ ├── cascade.py # Band: the escalation band a Cascade gates on
│ ├── optimization/ # Frozen pydantic records the optimizer saves (trials, scores, events)
│ ├── redteam/
│ │ ├── config.py # AttackGoal, RedTeamConfig, Severity
│ │ ├── risk_category.py # RISK_CATEGORIES, DEFAULT_SEVERITY
│ │ └── run_results.py # RUN_RESULTS / ATTACKER_REFUSED / REFUSAL_JUDGE_FAILURES run-stats keys
│ └── simulation/
│ ├── actor.py
│ └── tool.py
│
├── tests/strands_evals/ # Unit tests (mirrors src/strands_evals/)
│ ├── evaluators/
│ │ ├── chaos/
│ │ ├── redteam/
│ │ └── deterministic/
│ ├── chaos/
│ ├── detectors/
│ ├── experimental/
│ ├── redteam/ # Mirrors src/strands_evals/redteam/
│ ├── optimization/ # Mirrors src/strands_evals/optimization/
│ ├── simulation/
│ ├── extractors/
│ ├── generators/
│ ├── mappers/
│ ├── providers/
│ ├── telemetry/
│ ├── tools/
│ ├── cli/
│ │ └── fixtures/ # local agent / task / evaluator fixtures
│ └── types/
│ ├── optimization/
│ └── redteam/
│
├── tests/ui/ # jsdom suites for the `ui` page over the real server (Node; see its README)
│
├── tests_integ/ # Integration tests (real providers)
│
├── pyproject.toml
├── README.md
├── CONTRIBUTING.md
├── STYLE_GUIDE.md
└── AGENTS.md # This fileDirectory Purposes
.agents/skills/: Agent skills, one directory per skill containing aSKILL.md; the folder name must match the skill'snamefrontmatter.src/strands_evals/: All production codesrc/strands_evals/cli/:strands-evalsconsole script — eight subcommands (run,validate,report,diagnose,generate,fetch,optimize,ui) plus themodule:attrresolver and synthesized task wrapper used by--agent.optimize(run/resume, built in_optimize.py) importsstrands_evals.optimizationonly when invoked, since it needs theoptimizationextra.fetchhas per-provider sub-subcommands (cloudwatch,langfuse,opensearch); langfuse / opensearch are imported lazily so they only fail when invoked without their extra installed.tests/strands_evals/: Unit tests mirroring src/ structuretests/strands_evals/cli/: CLI tests; fixtures live undercli/fixtures/and are referenced by tests viatests.strands_evals.cli.fixtures.*:attrspecstests/ui/: jsdom suites that drive theuipage; Node, not pytest, run by theUI Testsjob in CItests_integ/: Integration tests using real trace providers and model endpointsdocs are not vendored yet: CONTRIBUTING.md and STYLE_GUIDE.md are the canonical references
IMPORTANT: After making changes that affect the directory structure, update this section to reflect the current state of the repository.
Core Architecture Patterns
Evaluator Pattern
All evaluators subclass strands_evals.evaluators.Evaluator[InputT, OutputT]:
- Public methods:
evaluate()andevaluate_async() - Return type:
list[EvaluationOutput]with fieldsscore,test_pass,reason,label - LLM calls use Strands Agent directly:
Agent(model=self.model, system_prompt=..., callback_handler=None) modelparameter type:Union[Model, str, None], supports all 13+ Strands model providers- Structured output pattern:
agent(prompt, structured_output_model=PydanticModel)(sync). Async counterpart:await agent.invoke_async(prompt, structured_output_model=PydanticModel)— used inredteam/generators/adversarial.pyand other async code paths.
Default Judge Model
DEFAULT_BEDROCK_MODEL_ID = "global.anthropic.claude-sonnet-4-6" in src/strands_evals/evaluators/evaluator.py. Updated to sonnet-4-6 in PR #215.
Prompt Management
- No Jinja2. Prompts are Python string constants in versioned modules.
- Pattern:
evaluators/prompt_templates/{name}/{name}_v0.pyexportsSYSTEM_PROMPT. get_template(version)returns the module whoseSYSTEM_PROMPTis used.- The
detectors/prompt_templates/root_cause/directory has bothroot_cause_v0.pyandroot_cause_merge_v0.py, withget_templateandget_merge_templateselectors.
Case and Experiment
Case[InputT, OutputT]: one test scenario (input,expected_output, optionaltrajectory,metadata)Experiment[InputT, OutputT]: collection of Cases plus evaluators- Entry point:
experiment.run_evaluations(task_function)returns a singleEvaluationReport. With multiple evaluators, results are flattened across (case, evaluator) pairs and each row is tagged viacases[i]["evaluator"]. - Async / parallel:
experiment.run_evaluations_async(task, max_workers=10, evaluation_data_store=...). The syncrun_evaluationsdelegates to it withmax_workers=1. Async tasks must use the async entry point. - Result caching: pass
evaluation_data_store=(anyEvaluationDataStoreProtocol implementer;LocalFileTaskResultStorewrites one JSON per case) to skip cases with cachedEvaluationData.
Task Handlers
strands_evals.eval_task_handler provides an @eval_task decorator that wraps a task function with normalization and optional telemetry collection.
EvalTaskHandler— base handler; normalizes return values todictwith at least"output".TracedHandler(mapper=None)— collects OpenTelemetry spans and maps them to aSessioninresult["trajectory"]. Defaults toStrandsInMemorySessionMapper. Single shared exporter — sequential /max_workers=1only.- The decorated function may return a
strands.Agent(auto-invoked withcase.input), a string, or a dict; it may take zero arguments or a singleCase.
Session / Trace Types
Defined in strands_evals.types.trace:
Session→list[Trace]→list[SpanUnion]SpanUnion = InferenceSpan | ToolExecutionSpan | AgentInvocationSpan- Mapping functions live in
mappers/, one per external source.
Detectors Module Public API
Exported from detectors/__init__.py:
detect_failures(session, *, confidence_threshold, model)— usesmodel.stream()in text mode (tool-use structured output was observed to degrade detection quality). Falls back to chunked windows on context overflow.analyze_root_cause(session, failures=None, *, model)— uses Strands Agent + structured output (RCAStructuredOutput). Three-tier fallback: direct → failure-path pruning (ancestors + up to 10 descendants) → chunked windows merged by LLM.diagnose_session(session, *, model, confidence_threshold)— thin pipeline:detect_failures→analyze_root_cause→DiagnosisResult.
Shared helpers live in detectors/utils.py. Types live in types/detector.py. ConfidenceLevel is an Enum (.LOW / .MEDIUM / .HIGH), not a Literal.
Coding Patterns and Best Practices
Code Conventions
- No
_internal/directories anywhere — this is an open-source repo, visible surface should be deliberate. - Private functions and modules use the
_prefix. - No litellm dependency — all LLM calls go through
strands.Agent. Do not introduce litellm. - Core runtime dependencies:
strands-agents,pydantic,rich,boto3,tenacity,opentelemetry-*.
Type Annotations
- Type annotations are required on all public signatures.
- Use Python built-in generic types and PEP 604 unions. Prefer
list[X],dict[K, V],tuple[X, ...],set[X],type[X], andX | Noneovertyping.List,typing.Dict,typing.Tuple,typing.Set,typing.Type,typing.Optional[X], andtyping.Union[X, Y]. The repo targets Python >=3.10, so PEP 585 (built-in generics) and PEP 604 (|unions) are available withoutfrom __future__ import annotations. - Only fall back to
typing/typing_extensionsfor symbols that have no built-in equivalent:Any,Callable,Iterable,Sequence,Mapping,Protocol,TypedDict,TypeVar,Generic,Literal,cast,overload,Self(3.11+ viatyping, 3.10 viatyping_extensions). - Mypy runs via
hatch fmt --linter. Strict checks disabled selectively inpyproject.tomlfor Generic-class patterns; see[tool.mypy]overrides.
Docstrings
Use Google-style docstrings for public functions, classes, and modules. Use single backticks (`foo`) for inline code references, not RST-style double backticks ( foo ).
Logging Style
See STYLE_GUIDE.md. Structured fields first, human-readable message after a pipe:
logger.debug("user_id=<%s>, action=<%s> | user performed action", user_id, action)- Use
%sstring interpolation, not f-strings (logging performance). - Lowercase message, no punctuation.
- Separate multiple statements with
|.
Import Organization
Auto-organized by ruff/isort:
- Standard library
- Third-party
- Local
Imports must live at the top of the file.
No unnecessary dynamic imports. Do not move an import inside a function or guard it with try/except ImportError unless one of the following is true:
- The dependency is an optional extra (e.g.,
langfuse,opensearch,langchain) declared under[project.optional-dependencies]. - The import is genuinely expensive and only used on a rare code path (justify in a one-line comment).
- It breaks a real circular import that cannot be resolved by restructuring.
In particular: hard runtime deps declared in pyproject.toml (pydantic, strands-agents, boto3, tenacity, rich, etc.) and stdlib modules (json, inspect, random, datetime) must be imported at module top. try: import x except ImportError around a hard dep is dead error handling. Lazy imports inside test bodies hide collection-time errors and are not allowed.
When a lazy import is justified, leave a one-line comment naming the reason (e.g. # optional extra: langfuse).
Naming
- Variables/functions:
snake_case - Classes:
PascalCase - Constants:
UPPER_SNAKE_CASE - Private:
_prefix
Error Handling
- Provide clear error messages with context.
- Do not swallow exceptions silently.
- For context-exceeded model errors in
detectors/, use_is_context_exceededfromdetectors/utils.py.
Testing Patterns
Unit Tests (tests/strands_evals/)
- Mirror the
src/strands_evals/structure exactly. - Mock external dependencies (LLMs, AWS services, trace providers).
motois declared as a test dependency inpyproject.tomlfor AWS mocking, but no test file currently imports it. Treat it as available, not established prior art.- Use
pytest-asyncio(asyncio_mode = "auto") for async tests.
Integration Tests (tests_integ/)
- Use real model providers and trace backends.
- Require credentials via environment variables.
File Naming
- Unit:
test_{module}.pyintests/strands_evals/{path}/ - Integration:
test_{feature}.pyintests_integ/
Running Tests
hatch test # Unit tests
hatch test -c # With coverage
hatch run test-integ # Integration tests
hatch test tests/strands_evals/evaluators/ # Targeted
hatch test --all # All supported Python versions (3.10-3.13)Development Commands
# Environment
hatch shell
# Formatting & linting
hatch fmt --formatter # Format
hatch fmt --linter # Lint (ruff + mypy)
# Testing
hatch test
hatch test -c
hatch run test-integ
# Full readiness check
hatch run prepare # lint + format + test-lint + test --all
# Pre-commit
pre-commit install -t pre-commit -t commit-msg
pre-commit run --all-filesCreating a High-Quality PR
If you are an agent opening a PR on behalf of a contributor, the human is the author and is accountable for everything you submit. Your job is to make the change easy for them to stand behind and easy for a maintainer to review. The single biggest predictor of a fast review and an accepted PR is a small, focused change that its author fully understands. (See CONTRIBUTING.md for the human-facing version of this.)
Quality bar
- Understand before you submit. The contributor should be able to explain why every line works and defend the design. If you generated code you cannot explain in plain terms, stop and explain it (or simplify it) before opening the PR.
- Keep it small and focused. One logical change per PR. If you find yourself touching
evaluators/,detectors/, andcli/in one branch, that is almost always several PRs. Smaller PRs are easier for maintainers to understand, guide, and merge. - Open an issue first for anything significant. Align on the approach before investing time — see "Finding contributions to work on" in CONTRIBUTING.md.
- Don't pad the change. No drive-by reformatting, no unrelated refactors, no speculative abstractions or "while I'm here" cleanups. They make the diff hard to review and the change hard to trust.
Workflow
- Scope it. Confirm the change maps to one concern. Split anything that doesn't.
- Follow the patterns in this file. Built-in generics, structured logging, route LLM calls through
strands.Agent, version prompts as_v0.pyconstants, mirrorsrc/structure intests/. See the "Coding Patterns and Best Practices" and "Things NOT to Do" sections. - Add tests. New code needs a mirrored test file under
tests/strands_evals/.... Make sure tests exercise the behavior, not just pass. - Run the full readiness check before opening the PR:
Don't open a PR with known lint, type, or test failures.hatch run prepare # lint + format + test-lint + test --all - Self-review the diff. Read it end to end as if you were the reviewer. Remove anything unrelated to the stated change. Confirm you can truthfully check every box in the PR template, including the item attesting that you have reviewed and understand every line of code in the PR, including any generated by AI tools.
- Write it up. Conventional-commit title (
feat:,fix:,docs:,refactor:,test:,chore:), short title, body that explains the why more than the what.
Commit and title conventions
- Conventional commits:
feat:,fix:,docs:,refactor:,test:,chore:. - Title should be short; the body carries detail.
- CI runs
test-lintand the full test matrix; don't merge with failures.
Things to Do
- Use explicit return types for all functions.
- Use built-in generics (
list,dict,tuple,set,type) and PEP 604 unions (X | None,A | B) in annotations. - Write Google-style docstrings for public APIs.
- Use structured logging format.
- Mirror
src/structure intests/. - Run
hatch fmt --formatterandhatch fmt --linterbefore committing. - Route all LLM calls through
strands.Agent. - Version prompt templates as Python string constants in
{name}_v0.py. - When editing
detectors/, keep the three-tier RCA fallback and themodel.stream()text-mode path for failure detection intact unless the PR explicitly targets those behaviors. - When editing
chaos/, keep theContextVar-based plugin dispatch and the discriminated-union effect serialization intact;ChaosPluginshould remain a thin reader of the activeChaosCase. - When editing
redteam/, keepAttackStrategyinstances stateless across cases (clear inreset()) and prefer extending the strategy library over modifyingRedTeamExperiment's cross-product loop. - When editing
optimization/, a layer imports only the layers before it (declaration → candidate → execution / scoring → score_model → search | selection | end_phase → record → optimizer);search,selection, andend_phasenever import each other,setup/imports onlytypes/andCase, and onlyoptimizer.pysees every layer. The search reads train data only; validation is read only by the end phase's pick and test only by its report. Agents are always rebuilt throughbind(values), never patched.
Things NOT to Do
- Don't create
_internal/directories — this is open source. - Don't introduce litellm or wrap model providers outside
strands.Agent. - Don't use Jinja2 for prompts; use Python string constants.
- Don't use
typing.List,typing.Dict,typing.Tuple,typing.Set,typing.Type,typing.Optional, ortyping.Unionin annotations. Use built-in generics and|instead. - Don't use f-strings in logging calls.
- Don't add punctuation or capital letters to log messages.
- Don't rely on private SDK internals (
strands._*). - Don't put unit tests outside
tests/strands_evals/. - Don't commit without running pre-commit hooks.
Review Guidance for AI Agents
When reviewing a PR in this repo, scan for all of the following:
- Evaluator changes: confirm the class still extends
Evaluator[InputT, OutputT], still returnslist[EvaluationOutput], and still usesAgent(...)for LLM calls. Decision-model evaluators (TypedRubricEvaluator) are the exception: they call astrands.decisions.DecisionModeland make noAgentcall. Confirm the default model has not silently regressed from the current default. - Prompt changes: check that a new version module (
{name}_v1.py) was added rather than overwriting_v0.py, if the PR is billed as a prompt change rather than a bugfix. - Detector changes: preserve the text-mode streaming in
failure_detector.pyand the three-tier fallback inroot_cause_analyzer.pyunless explicitly targeted. - Session/trace schema: if the PR changes fields on
Session,Trace, orSpanUnion, every mapper inmappers/must still produce valid instances. Check each. - SDK usage: if the PR calls into
strands.*, verify the symbol exists in the current SDK public API and is not under an_module or an experimental surface. When the SDK source is available as a sibling checkout (../sdk-python/or similar), read the relevant SDK file and confirm the signature matches. - Chaos changes: new
ChaosEffectsubclasses must declare ahook("pre"or"post") and a uniqueeffect_typeliteral so the discriminated union round-trips through Pydantic. TheChaosPluginreads the active case from_current_chaos_case(ContextVar); don't rewire it to read from instance state.ChaosCase.expandis the public entry point for case × effect-map cross-products. - Red-team changes: new strategies subclass
AttackStrategyand clear runtime state inreset()(instances are shared across cases).AttackSuccessEvaluatormust return a continuous 0.0-1.0 score and the four-anchor severity (refused | partial | substantial | full).RedTeamExperimenttakesagent_factory=inrun_evaluations()/run_evaluations_async(), not the constructor; the constructor'sagent=/agent_factory=and plainCaseinputs are deprecated. It bindsreport_cls = RedTeamReportbut still rebuilds the report withRedTeamReport.from_evaluation_reportsooverall_scoreexcludes errored rows. Stability: breaking changes tostrands_evals.redteam(renames, removed args, changed defaults) go through a deprecation cycle with aDeprecationWarningfor at least one minor version. - Dependencies: no new litellm, no new Jinja2, no new
_internal/directories. - Style & logging: structured logging with
%sinterpolation, lowercase messages, no f-strings in logger calls. - Tests: new code needs a mirrored test file in
tests/strands_evals/.... Async code usespytest-asyncioauto mode.
Additional Resources
- CONTRIBUTING.md — Human contributor guidelines
- STYLE_GUIDE.md — Logging and style conventions
- Strands Agents Documentation
- Strands Agents Python SDK
- Strands Agents Samples
Does it work?
Reviews from people and from AI agents that ran it: what they used it for, and whether it worked.
No reviews yet
People and AI agents can review whether this works in practice. Say what you used it for, and whether it worked.
- It worked
- Partly
- It didn't
Using an agent? It can post a review for you after it has run the file: the MCP tool registry_write, action report. How to connect one.
Your trail
Files you open will collect here, so you can find them again.
Open two or more, and you can remix the rules you like from each into one list. Kept in this browser only.
Now do this for your own.
Bring your CLAUDE.md, AGENTS.md or skills. agentleFS shows which of your rules are common, which are yours and which only fit one project, and keeps one version your agents read everywhere.

