[Update] I Tried Out the Harness Optimization Feature in Strands Evals

[Update] I Tried Out the Harness Optimization Feature in Strands Evals

I tried out the harness optimization newly added to Strands Evals! Strands keeps gaining more and more features...
2026.12.03

This page has been translated by machine translation. View original

Introduction

Hi, this is Jinno from the Consulting Department, currently enjoying re:Invent to the fullest.

Harness optimization has been released for Strands Evals!

https://strandsagents.com/blog/introducing-harness-optimization-strands-evals/

A new feature for Evals... Is it useful, I wonder!
I'll summarize the main changes and try it out right away!

Main changes

First, let's check what has changed!

It tunes your prompts and settings against your own test cases

Harness optimization was added as the strands_evals.optimization module in v1.12.0 (November 23, 2026) and introduced in the official blog on November 30.
If you mark the arguments of the function that assembles your agent as "OK to tune," it generates candidates for those arguments, runs them against your own test cases, and compares them.

What can be tuned here are text such as system prompts, tool descriptions, and skill files, as well as settings such as the depth of thinking (effort) and the method and thresholds of context management.

Previously, after looking at the scores in an evaluation, the developer read the failed conversations and fixed the prompt. With harness optimization, you add the items that may be changed and the objective to your current evaluation, and Strands Evals generates candidates, compares them with the same evaluation, and returns the changes as a diff

Differences from previous evaluation

Even with the previous Strands Evals, you could run an agent on prepared cases and have an evaluator assign scores.

However, when the score was low, you had to read the failed conversations and work out for yourself what to fix and how!
Harness optimization scores each candidate using the same combination of cases and evaluators, and goes on to handle everything from creating the candidates to comparing them.

The official documentation also says that if you have already written an evaluation, you should use that Experiment as is!

https://strandsagents.com/docs/user-guide/evals-sdk/optimization/quickstart/

Objectives and constraints can be written separately

What you want to improve is specified with an objective and constraints.
The objective is a single value to maximize or minimize, and constraints are the upper or lower bounds that the chosen settings must respect.

The official blog introduces the following two ways of writing them.

Example from the official blog
# Keep the average token consumption per case at 3,000 or less and maximize the accuracy rate
optimizer = Optimizer(
    experiment,
    create_agent,
    objective=Maximize("TaskSuccess"),
    constraints=[AtMost("tokens", 3000)],
)

# Minimize tokens while keeping the accuracy rate at 90% or higher
optimizer = Optimizer(
    experiment,
    create_agent,
    objective=Minimize("tokens"),
    constraints=[AtLeast("TaskSuccess", 0.9)],
)

It's easy to understand that you can write in code whether to prioritize accuracy or cost!

Results come back as a diff

Even after optimization finishes, your code stays unchanged, and the chosen changes are output to best.diff (text) and best.values.json (setting values). The design is that you review the contents and then apply them yourself.

The official blog reports results from running Claude Haiku 5.5 on the Strands harness against four public benchmarks. On τ²-bench telecom, the task success rate rose from 59.9% to 99.1%, and token consumption became 0.84 times as much.
This is a case where everything went perfectly, but it's impressive. It makes you want to do this kind of tuning.

Also usable from coding agents

Besides the Python SDK, you can use the optimize skill in tools such as Claude Code.
With the Strands CLI, you type /optimize in the strands dev chat.

This also looks easy to try, so I'd like to give it a go!

The optimization flow

Optimization proceeds by splitting the test cases into three sets: training, validation, and test.
For the 48 cases this time, it looked like the following figure.

The 48 inquiries are split into training, validation, and test sets; one candidate, created and tried on the training set, is selected on the validation set and compared against the current settings on the test set. The prompt candidates are created by a rewriter agent, and the effort candidates by Bayesian optimization

On the training cases, it creates and runs candidates, then creates the next candidates based on the scores, repeating this process. For text such as prompts, a Strands rewriter agent reads the conversation records and scores and rewrites it.

Settings determined by choices or numbers, such as effort, are selected by Bayesian optimization, which predicts promising next values from the scores so far.

When the search is over, one candidate is selected on the validation cases, and finally it is compared with the current settings on the test cases. Note that because the rewriter investigates logs with shell commands, running it in an environment with restricted permissions, such as a container, is recommended.

Prerequisites

Item Version / Value
strands-agents-evals 1.13.2
strands-harness 0.4.0
strands-agents 1.68.0
Python 3.15.2
uv 0.13.6
Region us-east-1
Agent model Claude Haiku 5.5 (us.anthropic.claude-haiku-5-5)
Rewriter model Claude Sonnet 5.5 (left as default)

AWS authentication is set up beforehand. Create a project and install it with the optimization extra.

Environment setup
mkdir strands-evals-optimize-try && cd strands-evals-optimize-try
uv init --bare
uv add 'strands-agents-evals[optimization]'

Trying it out

Create an agent that triages inquiries

The subject is an agent that reads inquiries arriving at an internal help desk and returns the category and priority in one line. I prepared 48 inquiries, 12 for each category.

agent.py (part of the tickets)
TICKETS = [
    ("パスワードを忘れてしまい、PCにログインできません。", "アカウント", "中"),
    ("営業部の全員がSalesforceにログインできなくなっています。", "アカウント", "高"),
    ("ノートPCの電源が入りません。今日は社内の資料作成だけの予定です。", "端末", "中"),
    ("出張先のホテルでVPNが切れやすいです。スマホのテザリングに切り替えて作業できています。", "ネットワーク", "低"),
    ("共有フォルダの閲覧権限を部下に付けたいです。", "申請", "低"),
    # ...
]

For the correct answers, I put in the following rules as if they were internal company rules, and did not write them in the prompt.

  • Requests asking for something to be newly prepared, added, or granted are "Request"
  • If communication with outside parties or the work of multiple people is stopped, the priority is "High"
  • If one person's work is stopped, it is "Medium"; if nobody's work is stopped, it is "Low"

The current prompt only conveys the candidates for category and priority and the output format.
Let's see whether the rewriter can pick up the rules from the conversations where the agent, not knowing the rules, failed.

agent.py (current prompt)
BASELINE_INSTRUCTIONS = """あなたは社内ヘルプデスクの一次受付です。
問い合わせを読んで、カテゴリと優先度を次の1行だけで答えてください。
カテゴリ: <アカウント|端末|ネットワーク|申請>、優先度: <高|中|低>"""

Mark the arguments that may be tuned

The agent is created with Strands harness's create_harness(). With @tunable, the prompt (TextValue) and effort (OneOf) are made tunable arguments. The default values of the arguments become the current settings.

agent.py (function that creates the agent)
@tunable(instructions=TextValue(), effort=OneOf("high", "medium", "low"))
def create_agent(instructions=BASELINE_INSTRUCTIONS, effort="high"):
    return create_harness(
        model="bedrock/us.anthropic.claude-haiku-5-5",
        effort=effort,
        instructions=instructions,
        builtin_tools=[],
        skills=False,
        memory=False,
        session=False,
        callback_handler=None,
    )

Since temperature is deprecated and causes an error with Haiku 5.5, this time I targeted effort, which changes the depth of thinking.

Decide how to score

Scoring is done in code. If the answer is in one line and both category and priority match, it scores 1.0. If only the category matches, 0.5; otherwise 0.

agent.py (scoring)
class Triage(Evaluator[str, str]):
    def evaluate(self, case: EvaluationData[str, str]) -> list[EvaluationOutput]:
        expected = LINE.search(case.expected_output)
        lines = [line for line in str(case.actual_output).strip().splitlines() if line.strip()]
        actual = LINE.search(lines[0]) if len(lines) == 1 else None
        if actual is None:
            score, reason = 0.0, "「カテゴリ: X、優先度: Y」の1行になっていない"
        elif actual.groups() == expected.groups():
            score, reason = 1.0, "カテゴリと優先度が一致"
        elif actual.group(1) == expected.group(1):
            score, reason = 0.5, f"優先度が違う(期待: {expected.group(2)})"
        else:
            score, reason = 0.0, f"カテゴリが違う(期待: {expected.group(1)})"
        return [EvaluationOutput(score=score, test_pass=score == 1.0, reason=reason)]

Because no LLM evaluator is used, there are no evaluation tokens.

Write the objective and constraints and run

The objective is to maximize the average score of Triage, and the constraint is "average token consumption per case up to 1.5 times the current settings."

agent.py (running the optimization)
optimizer = Optimizer(
    experiment,
    create_agent,
    objective=Maximize("Triage"),
    constraints=[AtMost("tokens", baseline_ratio=1.5)],
    budget=Budget(max_rollouts=350),
    max_workers=16,
)
result = optimizer.run()
print(result.summary())

The budget is specified as the number of agent runs (rollouts), and I set it to 350 this time. Incidentally, I initially fixed the limit at 1,000 tokens, but the system prompt alone is about 1,700 tokens, so every candidate exceeded the limit and it ended with nothing changed. When using a fixed value, it's safest to check the current token count first.

Full agent.py
agent.py
import re

from strands_evals import Case, Experiment
from strands_evals.evaluators import Evaluator
from strands_evals.types.evaluation import EvaluationData, EvaluationOutput
from strands_evals.optimization import (
    AtMost,
    Budget,
    Maximize,
    OneOf,
    Optimizer,
    TextValue,
    tunable,
)
from strands_harness import create_harness

MODEL_ID = "us.anthropic.claude-haiku-5-5"

# (問い合わせ, カテゴリ, 優先度)
# プロンプトには書かず、期待値にだけ反映しているルール
# カテゴリ: 新しく用意・追加・付与・貸し出してほしい依頼は申請。今あるものが使えないときは原因で分ける
# 優先度: 社外とのやりとりか複数人の作業が止まっていたら高、1人の作業が止まっていたら中、
#         誰の作業も止まっていなければ低(質問・要望・申請、代わりの手段で作業できている場合)
TICKETS = [
    ("パスワードを忘れてしまい、PCにログインできません。", "アカウント", "中"),
    ("営業部の全員がSalesforceにログインできなくなっています。", "アカウント", "高"),
    ("機種変更したので、多要素認証のアプリを新しいスマホに移したいです。今は古いスマホで認証できています。", "アカウント", "低"),
    ("お客さまとの共有フォルダに今朝からアクセスできず、納品データを渡せません。", "アカウント", "高"),
    ("退職者のアカウントはいつ削除されますか?", "アカウント", "低"),
    ("アカウントがロックされたとメッセージが出て、メールが見られません。", "アカウント", "中"),
    ("パスワードの有効期限は何日ですか?", "アカウント", "低"),
    ("経理システムにログインすると「権限がありません」と出て、自分の担当の伝票が入力できません。", "アカウント", "中"),
    ("チーム全員がTeamsにサインインできず、朝会が始められません。", "アカウント", "高"),
    ("取引先とのチャットに使っている外部共有アカウントにログインできず、問い合わせに返信できません。", "アカウント", "高"),
    ("多要素認証のコードがスマホに届かず、勤怠システムに入れません。", "アカウント", "中"),
    ("シングルサインオンの仕組みについて教えてください。", "アカウント", "低"),
    ("ノートPCの電源が入りません。今日は社内の資料作成だけの予定です。", "端末", "中"),
    ("10分後のお客さまとのオンライン商談で、PCのマイクが認識されません。", "端末", "高"),
    ("キーボードのいくつかのキーが反応しにくいです。外付けキーボードで作業はできています。", "端末", "低"),
    ("経理課の共有プリンターが紙詰まりのエラーで、課の誰も印刷できません。", "端末", "高"),
    ("PCの動作がとても重く、Excelを開くのに数分かかって作業が進みません。", "端末", "中"),
    ("画面の明るさを変える方法を教えてください。", "端末", "低"),
    ("会議室のプロジェクターが映らず、これから始まる部内会議(15人)が始められません。", "端末", "高"),
    ("PCのバッテリーが2時間しか持たなくなりました。", "端末", "低"),
    ("ブルースクリーンが繰り返し出て、作業中のファイルを開けません。", "端末", "中"),
    ("お客さまに見せるデモ用のタブレットが起動せず、訪問先でデモができません。", "端末", "高"),
    ("マウスのホイールが効きにくいですが、使えないほどではありません。", "端末", "低"),
    ("モニターが映らなくなりましたが、ノートPCの画面で作業を続けています。", "端末", "低"),
    ("3階のフロア全体でWi-Fiがつながりません。", "ネットワーク", "高"),
    ("自宅からVPNにつながらず、社内システムが使えません。", "ネットワーク", "中"),
    ("取引先とのWeb会議の途中で何度も通信が切れて、会議が続けられません。", "ネットワーク", "高"),
    ("会議室のWi-Fiが少し遅い気がします。今のところ困ってはいません。", "ネットワーク", "低"),
    ("来客用Wi-Fiのパスワードはどこで確認できますか?", "ネットワーク", "低"),
    ("自席の有線LANだけつながりません。他の人は問題ないようです。", "ネットワーク", "中"),
    ("大阪支社の全員が社内システムにつながらない状態です。", "ネットワーク", "高"),
    ("出張先のホテルでVPNが切れやすいです。スマホのテザリングに切り替えて作業できています。", "ネットワーク", "低"),
    ("社外へのインターネット通信だけができず、お客さまにメールを送れません。", "ネットワーク", "高"),
    ("開発チームの5人とも社内のGitサーバーに接続できません。", "ネットワーク", "高"),
    ("在宅勤務で使う回線の推奨速度を教えてください。", "ネットワーク", "低"),
    ("自分のPCだけWi-Fiの一覧に社内のネットワークが出てこず、仕事ができません。", "ネットワーク", "中"),
    ("モニターをもう1台追加してほしいです。", "申請", "低"),
    ("画像編集ソフトをインストールしたいので許可をください。", "申請", "低"),
    ("来週入社する2名分のPCとアカウントを用意してください。", "申請", "低"),
    ("お客さま先で使うプレゼン用のノートPCを明日から3日間借りたいです。", "申請", "低"),
    ("共有フォルダの閲覧権限を部下に付けたいです。", "申請", "低"),
    ("マウスが壊れたので新しいものを申請したいです。今は予備のマウスを使っています。", "申請", "低"),
    ("新しく始まるプロジェクトのメーリングリストを作ってください。", "申請", "低"),
    ("経理システムの承認者に私を追加してください。", "申請", "低"),
    ("来月から来る協力会社の方に、ゲスト用のアカウントを発行してください。", "申請", "低"),
    ("在宅勤務用にヘッドセットを1つ支給してほしいです。", "申請", "低"),
    ("今日から来た派遣社員の方のアカウントがまだなく、作業を始められません。", "申請", "中"),
    ("今日から参加する協力会社の3名に作業用フォルダの権限を付けてください。まだ誰も作業を始められていません。", "申請", "高"),
]

LINE = re.compile(r"カテゴリ[::]\s*(\S+?)[、,]\s*優先度[::]\s*(\S+)")

class Triage(Evaluator[str, str]):
    """1行でカテゴリと優先度が両方合えば1.0、カテゴリだけ合えば0.5"""

    def evaluate(self, case: EvaluationData[str, str]) -> list[EvaluationOutput]:
        expected = LINE.search(case.expected_output)
        lines = [line for line in str(case.actual_output).strip().splitlines() if line.strip()]
        actual = LINE.search(lines[0]) if len(lines) == 1 else None
        if actual is None:
            score, reason = 0.0, "「カテゴリ: X、優先度: Y」の1行になっていない"
        elif actual.groups() == expected.groups():
            score, reason = 1.0, "カテゴリと優先度が一致"
        elif actual.group(1) == expected.group(1):
            score, reason = 0.5, f"優先度が違う(期待: {expected.group(2)})"
        else:
            score, reason = 0.0, f"カテゴリが違う(期待: {expected.group(1)})"
        return [EvaluationOutput(score=score, test_pass=score == 1.0, reason=reason)]

    async def evaluate_async(self, case: EvaluationData[str, str]) -> list[EvaluationOutput]:
        return self.evaluate(case)

experiment = Experiment(
    cases=[
        Case(name=f"ticket-{i:02d}", input=text, expected_output=f"カテゴリ: {category}、優先度: {priority}")
        for i, (text, category, priority) in enumerate(TICKETS)
    ],
    evaluators=[Triage()],
)

BASELINE_INSTRUCTIONS = """あなたは社内ヘルプデスクの一次受付です。
問い合わせを読んで、カテゴリと優先度を次の1行だけで答えてください。
カテゴリ: <アカウント|端末|ネットワーク|申請>、優先度: <高|中|低>"""

@tunable(instructions=TextValue(), effort=OneOf("high", "medium", "low"))
def create_agent(instructions=BASELINE_INSTRUCTIONS, effort="high"):
    return create_harness(
        model=f"bedrock/{MODEL_ID}",
        effort=effort,
        instructions=instructions,
        builtin_tools=[],
        skills=False,
        memory=False,
        session=False,
        callback_handler=None,
    )

if __name__ == "__main__":
    optimizer = Optimizer(
        experiment,
        create_agent,
        objective=Maximize("Triage"),
        constraints=[AtMost("tokens", baseline_ratio=1.5)],
        budget=Budget(max_rollouts=350),
        max_workers=16,
    )
    result = optimizer.run()
    print(result.summary())
Run
uv run agent.py

It finished in about four and a half minutes, and the summary of results was displayed.

Execution result (excerpt)
Constraints:    tokens <= 2946.55 (baseline 1964.37 * 1.5)
Stop reason:    budget                Rollouts:   335 / 350
Champion:       candidate 5           Outcome:    top_finalist
Changed:        effort, instructions
======================================================================================================================
Validation     id            goal                                      estimate     sd  measured   n  P(met)  status
----------------------------------------------------------------------------------------------------------------------
baseline       8c6bc28ced97  Triage                                       0.770  0.047     0.767  15          feasible
candidate 5 *  79dc41b66689  Triage                                       0.841  0.044     0.867  15          feasible
======================================================================================================================
Test vs baseline  baseline  champion    diff            90% CI   n
----------------------------------------------------------------------------------------------------------------------
Triage               0.821     0.893  +0.071  [-0.085, +0.228]  14
tokens               1,931     2,428    +497      [+450, +545]  14

Candidate 5, which rose from 0.77 to 0.87 on the 15 validation cases, was selected, and the average score on the 14 test cases also rose from 0.821 to 0.893!

However, the 90% interval of the test difference is -0.085 to +0.228, which spans 0. I appreciate that it reports the result as is, saying that with 14 cases we can't claim it got better. The average token consumption increased by 497, but it stays within the 1.5x limit.

Look at the rewritten prompt

The prompt changes are output to best.diff in the run folder under optimization/runs/.

best.diff
--- instructions
+++ instructions
@@ -1,3 +1,15 @@
 あなたは社内ヘルプデスクの一次受付です。
-問い合わせを読んで、カテゴリと優先度を次の1行だけで答えてください。
-カテゴリ: <アカウント|端末|ネットワーク|申請>、優先度: <高|中|低>
\ No newline at end of file
+問い合わせを読んで、カテゴリと優先度を次の1行だけで答えてください(説明は書かない)。
+カテゴリ: <アカウント|端末|ネットワーク|申請>、優先度: <高|中|低>
+
+【カテゴリ】
+- 申請: 新規の発行・作成・追加・権限付与・備品の追加などを「依頼」するもの(新規/ゲスト/派遣のアカウント発行、フォルダ権限付与、メーリングリスト作成、機器の追加など)。アカウントという語が出ても、新しく作る・付ける依頼なら申請。
+- アカウント: 既存アカウントのトラブル(ログイン不可、パスワード忘れ、ロック、認証)や認証の質問。
+- 端末: PC・モニター・キーボード・タブレット・プリンターなど機器の故障や不具合。
+- ネットワーク: 通信・Wi-Fi・社内サーバー接続の問題や質問。
+
+【優先度】影響の大きさと緊急性で決める。
+- 高: 複数人・部署全体が影響を受ける、または業務が止まっていて今日中の対応が必要(顧客対応・デモなど期限が迫る場合も含む)。
+- 中: 影響が本人1人で、業務は支障があるが代替手段がない/不明確、または通常の対応でよいもの(個人のログイン不可・ロック・パスワード忘れ・個人のPC故障・権限エラー)。
+- 低: 代替手段で作業できている、困っていない、単なる質問、急ぎでない将来の依頼や備品追加。
+個人1人の問題は、業務が止まっていても原則「中」。複数人・全員・誰も作業できない場合や期限が迫る場合だけ「高」。出力例: カテゴリ: 申請、優先度: 低

The rule for requests that was not in the prompt has been added as "even if the word 'account' appears, a request to newly create or attach something is a request"! For priority too, it has become the rule that a problem for one person is in principle "Medium," and "Low" if work can be done by an alternative means, which is quite close to the correct answer.

On the other hand, "High if communication with outside parties stops" was replaced by the condition "when a deadline is approaching, such as customer support or a demo." The following six cases among the 14 test cases had their answers changed.

Inquiry Correct answer Current settings Selected settings
My PC is very slow... I can't get any work done Medium High Medium
I can't connect to the VPN from home... Medium High Medium
The VPN drops easily at the hotel on my business trip. ... I can work using tethering Low Medium Low
Please add me as an approver in the accounting system Low Medium Low
My PC's battery only lasts two hours now Low Low Medium
Only internet communication to the outside is down, and I can't send emails to customers High High Medium

Four got better and two got worse, so it seems best to add the condition "High if communication with outside parties stops" before applying it. Since the design returns a diff that you apply yourself, it's easy to slip in this kind of manual touch-up.

See which change raised the score

Changes to setting values are output to best.values.json in the same folder, and effort changed from high to medium. Which change moved the score can be checked with result.effects (or effects.json in the same folder).

Displaying the effects
for row in result.effects["effects"]:
    low, high = row["ci90"]
    print(f'{row["metric"]}: {row["key"]}={row["level"]} vs {row["reference"]}: '
          f'{row["mean"]:+.3g} [{low:+.3g}, {high:+.3g}]')
Execution result
Triage: effort=medium vs high: +0.0127 [-0.0163, +0.0418]
Triage: effort=low vs high: -0.00749 [-0.0356, +0.0206]
Triage: rewritten:text=rewritten vs default: +0.169 [+0.115, +0.223]
tokens: effort=medium vs high: +22.4 [-109, +154]
tokens: effort=low vs high: -36.7 [-192, +118]
tokens: rewritten:text=rewritten vs default: +516 [+370, +662]

What pushed the score up was the prompt rewrite (+0.169), and for the effort change, the 90% intervals for both score and tokens span 0. The official documentation also advises keeping the current value for settings with no observable effect, so this time it seems best to leave effort at high and adopt only the prompt.

https://strandsagents.com/docs/user-guide/evals-sdk/optimization/results/

Tokens used

At the end of the results summary, a breakdown of tokens is also shown.

Execution result (excerpt)
Tokens               search  validation    test      total  failed
----------------------------------------------------------------------------------------------------------------------
agent               605,248     140,053  61,032    806,333       0
judges                    0           0       0          0       0
proposer text       640,256           0       0    640,256       0
total             1,245,504     140,053  61,032  1,446,589       -

The agent, Haiku 5.5, used about 810,000 tokens and the rewriter, Sonnet 5.5, about 640,000 tokens, and most of both were reads from the cache. Calculated at Bedrock's unit prices, the total came to just under 1 dollar.
Since Sonnet has a higher unit price, most of the cost is the rewriter's share.

Conclusion

I tried harness optimization in Strands Evals!
It was interesting that it picked up the internal company rules that were not written in the prompt from the failed conversations and wrote them in.
Next time, I'd like to try how far the difference interval narrows when the number of test cases is increased, how effective it is with more complex agents, and also tuning of tool descriptions and skills!!

I hope this article is of some help. Thank you for reading to the end!

Share this article

AWSのお困り事はクラスメソッドへ