AgentCore Model Override: Test a Second Model in the Same Session
Use an AgentCore model override to try Amazon Ergo for one turn in Python. Check same-session recall against a fresh session and verify the harness default.
Your AgentCore harness already handles follow-up questions. Before adding a second model to your application, you want to know whether switching models halfway through a conversation preserves the facts the user already supplied. An AgentCore model override lets you try the switch on a single request. In this Python test, the default model receives a synthetic return policy, a request for Amazon Ergo asks about it in the original session, and a third turn uses the harness default. A fresh-session control and two configuration reads give you distinct checks on the result.
AWS announced AgentCore harness support for Amazon Ergo on December 1, 2026, including selection for a single invocation through a Bedrock cross-Region inference profile. This tutorial uses the US Geo profile from a harness in Oregon. AWS announcement

Choose the sandbox and establish the baseline
- Use Python 3.10 or later and a boto3 installation that exposes
get_harnessonbedrock-agentcore-controlandinvoke_harnessonbedrock-agentcore. Bring an already deployed, IAM-authenticated sandbox harness inus-west-2. Have its harness ID handy, such asMyHarness-XyZ1234567in AWS’s example. The script reads the actual ARN from AWS, so the ID is the only resource identifier you supply. AWS SDK setup · Boto3 GetHarness reference - Start with an effectively tool-free, text-only harness with working same-session history and no external fixture sources. Confirm that its instructions permit short literal replies and that its effective tools, skills and hooks cannot introduce actions or additional context. Ask the deployment owner about effective tool selection. AWS documents that a wildcard can include recommended built-in tools even when the list of custom tool definitions is empty. Use synthetic input throughout. Managed memory may persist test events and incur charges. Harness security · Harness memory
- Confirm the two identities. The Python caller needs
bedrock-agentcore:GetHarnessfor the reads and bothbedrock-agentcore:InvokeHarnessandbedrock-agentcore:InvokeAgentRuntimefor invocation. The harness execution role needs its existing default-model access and authorization for inference through the Ergo profile. AWS’s execution-role example identifiesbedrock:InvokeModelandbedrock:InvokeModelWithResponseStreamand discusses scoping to the profile and underlying model resources. Ask the role owner to confirm that scope before you run. Harness security
The control-plane read and runtime call need to refer to the same deployment. The script asks for the current configuration by omitting harnessVersion from GetHarness. It omits qualifier on InvokeHarness, which selects the DEFAULT endpoint. AWS documents that this endpoint tracks the latest version. Run on a ready sandbox during a period without deployments. In that setup, the current harness read is the baseline for the test. A named endpoint can point to a different version, so a current-config read paired with a named endpoint would compare settings for a potentially different invocation target. GetHarness API · InvokeHarness API · Harness versioning
Use a sandbox whose effective default is a different Bedrock model. The example checks the returned model ID against the three documented Ergo identifiers before sending prompts. If your organization uses a separately named profile, confirm with the deployment owner which model that profile resolves to. The script also requires a model configuration in the readback and checks harness status before and after the calls. AWS says the read returns effective values, including service defaults. Use the value AWS returns even if your infrastructure code leaves model selection to the service. Harness memory · Models and instructions
The Region passed to boto3 is where the harness runs and where inference originates in this example. The model value is us.amazon.ergo-1.0, the Bedrock US Geo inference profile. AWS lists Oregon as a supported AgentCore source Region for this integration. The Ergo model card lists Ohio as the destination for US Geo requests originating there. Keep us-west-2 on both clients and the us. prefix on the model ID. Those two settings identify the source Region and the inference profile respectively. AWS announcement · Amazon Ergo model card
Design a follow-up that withholds the answer
- Plant the synthetic values
POL-17and30 daystogether on the first turn of the main session. The reply requested on that turn isSTORED. That word is an acknowledgment for the script to check. It takes a separate recall request to find out whether the harness carries the information forward. - Ask for the earlier ticket and return window in a particular format. The follow-up supplies the names of the fields and a separator but leaves both values out. Keep the string identical between the main follow-up and the fresh-session negative control. Use one new actor ID for the run and distinct session IDs for the two arms. AWS documents that memory events are scoped by actor and session, and describes automatic long-term retrieval when active strategies are configured. The script runs the fresh-session control before planting the fixture anywhere under that actor. Harness memory
- Request the same Ergo profile in both recall calls. The control gathers an initial, unseeded response, and the main follow-up tests recall after the default model received the fixture. Then ask for
DEFAULT_OKon the main session with the model field absent. Keep that last prompt independent of recall so you can check whether the default turn completes even when the main recall text misses the answer key.
The fixture uses two pieces of information because a return window on its own is easy to guess. A model can say 30 days by coincidence. Asking for the exact synthetic ticket as well gives the assertion a more specific target. A fresh model might still invent another ticket or a conventional return window. The control expects the explicit UNKNOWN response requested by the prompt so that a guess, even an incorrect one, fails visibly.
The control helps you test whether an unseeded call can already produce the answer, for example because the fixture appears in the fixed system instructions. Its position before the seed limits the result to an unseeded session at the start of the run. Testing retrieval in a new session after seeding would require another experiment with known memory strategies and namespaces. Keep concurrent test runs and other conversations off the actor used here. Harness memory
Keep the answer key local to the script. Check request construction if you integrate the test into existing application code. A wrapper that prepends a transcript or adds the policy to the system prompt gives the recall turn another path to the answer. Both recall requests should carry the same current user message and the same model configuration. Even a small change such as supplying the ticket as a hint in one arm weakens the comparison because the two prompts then ask the model to recover different amounts of information. InvokeHarness API
| Input | Action | Expected result |
|---|---|---|
task:pol-17-override, fresh control session and no seeded ticket |
Send the follow-up with model.bedrockModelConfig.modelId set to us.amazon.ergo-1.0 through InvokeHarness. |
Illustrative expected observation is assistant text UNKNOWN and a stream ending normally with end_turn. |
task:pol-17-override, main session, ticket POL-17, return window 30 days |
Send the fixture on a new runtimeSessionId with the model field omitted. |
Illustrative expected observation is assistant text STORED and end_turn. |
task:pol-17-override, same main runtimeSessionId |
Send the exact control prompt again with the same Ergo override and no replay of the seed message. | Illustrative expected observation is POL-17 / 30 days and end_turn. |
task:pol-17-override, third main-session turn and baseline saved |
Omit model on InvokeHarness, then call GetHarness for the current configuration again. |
Illustrative expected observation is DEFAULT_OK and matching model configuration and harness version in the two reads. |
Run the four calls from Python
- Save the complete example as
agentcore_override.pyin the environment where your authorized AWS identity and compatible SDK are already configured. - Run
python agentcore_override.py MyHarness-XyZ1234567, replacing the example ID with your Oregon sandbox harness ID. The script prints the baseline model ID and version before the first inference request. It labels each request with the model value it passes to boto3 or<omitted>. - Read the four labeled replies and five
PASSorFAILlines. The script exits with status zero when all five checks pass and one if a comparison fails. A service or stream exception terminates the run. The stage printed immediately before the call identifies where to start investigating. The script and expected outputs are illustrative. The example was prepared against the AWS references and was not run against a live harness for this article.
import argparse
from uuid import uuid4
import boto3
REGION = 'us-west-2'
ERGO = 'us.amazon.ergo-1.0'
EXPECTED = 'POL-17 / 30 days'
SEED = (
'Fictional return policy for this conversation. '
'The ticket is POL-17 and its return window is 30 days. '
'Reply with STORED only.'
)
FOLLOW_UP = (
'What ticket and return window were supplied earlier in this conversation? '
'Reply with the ticket, a space, a slash, a space, then the window in days '
'using digits and the word days. If either value is missing, reply UNKNOWN. '
'Return only the answer.'
)
def read_harness(control, harness_id, stage):
print(stage, flush=True)
harness = control.get_harness(harnessId=harness_id)['harness']
if harness['status'] != 'READY':
raise RuntimeError(f'{stage}: harness status is {harness["status"]}')
if not harness.get('model') or not harness.get('harnessVersion'):
raise RuntimeError(f'{stage}: missing effective model or harness version')
return harness
def invoke(runtime, arn, session_id, actor_id, prompt, stage, model_id=None):
request = {
'harnessArn': arn,
'runtimeSessionId': session_id,
'actorId': actor_id,
'messages': [{'role': 'user', 'content': [{'text': prompt}]}],
}
if model_id is not None:
request['model'] = {'bedrockModelConfig': {'modelId': model_id}}
print(f'{stage} session={session_id} requested_model={model_id or "<omitted>"}',
flush=True)
text_parts = []
role = None
stop_reason = None
error_events = ('runtimeClientError', 'validationException', 'internalServerException')
try:
stream = runtime.invoke_harness(**request)['stream']
try:
for event in stream:
for name in error_events:
if name in event:
raise RuntimeError(f'{name}: {event[name]}')
if 'messageStart' in event:
role = event['messageStart']['role']
stop_reason = None
if role == 'assistant' and 'contentBlockDelta' in event:
delta = event['contentBlockDelta']['delta']
if 'text' in delta:
text_parts.append(delta['text'])
if 'messageStop' in event:
stop_reason = event['messageStop']['stopReason']
finally:
stream.close()
except Exception as exc:
raise RuntimeError(f'{stage}: invocation or stream failed') from exc
reply = ''.join(text_parts).strip()
if stop_reason != 'end_turn' or not reply:
raise RuntimeError(f'{stage}: incomplete text turn (stop={stop_reason!r})')
print(f'{stage} stop={stop_reason} reply={reply!r}', flush=True)
return reply
def main():
parser = argparse.ArgumentParser(description='Test a one-turn Ergo override')
parser.add_argument('harness_id')
args = parser.parse_args()
control = boto3.client('bedrock-agentcore-control', region_name=REGION)
runtime = boto3.client('bedrock-agentcore', region_name=REGION)
if not hasattr(control, 'get_harness') or not hasattr(runtime, 'invoke_harness'):
parser.error('Install an SDK that exposes get_harness and invoke_harness')
before = read_harness(control, args.harness_id, 'baseline GetHarness')
default_id = before['model'].get('bedrockModelConfig', {}).get('modelId')
if not default_id or default_id in {ERGO, 'global.amazon.ergo-1.0', 'amazon.ergo-1.0'}:
parser.error('Use a sandbox with a different effective Bedrock default model')
print(f'baseline model={default_id} version={before["harnessVersion"]}', flush=True)
arn = before['arn']
actor = f'override-test-{uuid4()}'
control_session = str(uuid4())
main_session = str(uuid4())
control_reply = invoke(runtime, arn, control_session, actor, FOLLOW_UP,
'fresh control', model_id=ERGO)
seed_reply = invoke(runtime, arn, main_session, actor, SEED, 'turn 1 seed')
recall_reply = invoke(runtime, arn, main_session, actor, FOLLOW_UP,
'turn 2 recall', model_id=ERGO)
default_reply = invoke(runtime, arn, main_session, actor,
'Reply with DEFAULT_OK only.', 'turn 3 default')
after = read_harness(control, args.harness_id, 'final GetHarness')
checks = {
'fresh control': control_reply == 'UNKNOWN',
'seed acknowledgment': seed_reply == 'STORED',
'same-session recall': recall_reply == EXPECTED,
'default turn reply': default_reply == 'DEFAULT_OK',
'default and version match': (
before['model'] == after['model']
and before['harnessVersion'] == after['harnessVersion']
),
}
for label, passed in checks.items():
print(f'{"PASS" if passed else "FAIL"} {label}')
return 0 if all(checks.values()) else 1
if __name__ == '__main__':
raise SystemExit(main())
Each request gets a new dictionary. Turns one and three therefore carry no model key, even though the preceding request in each case used an override. The Ergo calls supply one member of the model configuration union, bedrockModelConfig. AWS documents converse_stream as the default for that member, so the example leaves apiFormat at its default and adds no provider parameters. The only message sent per call is the new user text. The session UUID, a 36-character string, satisfies the API’s 33-to-100-character constraint and tells the harness which conversation to continue. Models and instructions · InvokeHarness API
Read the entire response stream before judging an answer. The SDK example in AWS’s guide iterates response['stream'] and reads text from contentBlockDelta. The collector joins assistant text fragments without inserting separators. For instance, POL- and 17 / 30 days in successive fragments reconstruct the exact answer. The collector skips reasoning and usage fields, checks documented error events, and requires a nonempty reply with a final end_turn. A plausible fragment followed by a runtime error cannot pass the test. AWS streaming response guide · InvokeHarness API
The script waits for one stream to finish before sending the next message. If you move this sequence into an application that consumes streams in the background, wait for the seed stream to complete before submitting recall. Otherwise the test introduces overlapping requests into a sequence designed around completed turns. Read the lines in pairs when debugging. The line with a session ID is printed before the request goes out. The line with a stop reason and reply is printed after the stream has been consumed and checked. If you have the first line alone, look for the exception to learn how far the call got. AWS streaming response guide
In an illustrative successful run, the first request and the recall request print requested_model=us.amazon.ergo-1.0, while the seed and default turns print requested_model=<omitted>. The last three request lines share one session ID. The control request line has a different ID. Check those pairings before looking at the text comparisons if you have moved the example into an application. A matching answer obtained with a replayed transcript or a different session ID answers a different question from the one in the worked example.
Read the replies and the deployment check separately
| Observation | Interpretation and next action |
|---|---|
Both recall calls request the exact US Geo profile, control returns UNKNOWN, and seeded recall returns POL-17 / 30 days. |
Record a successful recall test under the explicit override. Keep both session IDs and the reply text with the result. |
Both recall calls return POL-17 / 30 days. |
Treat the comparison as inconclusive. Verify that the sandbox instructions and other reachable sources lack the fixture, and confirm the two request session IDs differ. |
The control returns UNKNOWN and seeded recall returns UNKNOWN or a different value. |
Inspect the seed acknowledgment and the emitted main-session IDs. Check that session history is available and the sandbox instructions support the requested response. |
| The model configuration or harness version differs in the final read. | Treat the deployment comparison as failed. Identify the configuration change and repeat once the sandbox is stable. |
The requested_model line records the selection your code supplies to boto3. The API contract describes how AgentCore uses that configuration. The published stream metadata reports usage and latency. If your acceptance criterion requires positive identification of the model that served each call, collect separate evidence for that criterion. For a discussion of served-model provenance, see Who Actually Answered? · InvokeHarness API
The two recall replies test what information was available to answer the same question. Reusing the session ID continues the conversation, and the absence of the answer from the new request gives a correct reply its evidentiary value. The exact comparison tolerates surrounding whitespace. If a reply says POL-17 / 30 days. with a final period, inspect it as a format mismatch even though a human can see both facts. If you adapt the script to accept punctuation, make that rule explicit and keep the same scoring across runs. Otherwise a changed comparison can look like an improvement in recall.
Turn three checks that a request with model omitted can complete after the override. DEFAULT_OK tests whether the request finished with the expected text. Comparing the entire effective model object before and after includes any model settings returned by AWS. Comparing harnessVersion catches a successful deployment update that leaves the model ID untouched. The reads bracket the experiment and report what AWS returned at those two moments. The documented behavior of DEFAULT connects that configuration check to the invocation target. Boto3 GetHarness reference · Harness versioning
Suppose the seeded reply matches the answer key and the last model ID looks familiar, but the harness version comparison fails. Open the two version records through your deployment tooling and check whether an update landed during the run. Even a system prompt or limit change could affect your interpretation because each version contains a complete configuration. Repeat from a new session once the intended version is serving the default endpoint. If the final read itself fails, keep the recall observation with its session ID and mark the configuration comparison incomplete. Use a full rerun to obtain a fresh pair of reads around the same four calls. Harness versioning
If you keep a record of the test, put the two session IDs next to the model request and the response text. Keep the version comparison on its own line so a deployment change stays visible alongside successful recall. The same practice helps when checking a change to a stream parser or selecting synthetic values for a regression test. See Replay One Response Through Two Adapters and Build a Simulated Company for Agent Testing. For what to log when an application owns the agent loop, see AgentOps.
Recover from profile, IAM and stream failures
- Locate the failed stage before changing anything. A denied baseline read points to the caller’s
GetHarnessaccess. A rejected invocation with HTTP 403 calls for checking the caller’s two invocation actions on the intended harness. If the default path works separately and the runtime error on an Ergo turn mentions model access, inspect the harness execution role’s scope for the Ergo inference profile and the model resources it uses. A runtime client error has several possible causes, so use its message to distinguish permission, network and configuration problems. Harness security · InvokeHarness API - Check the Region and profile when validation fails. The script targets an Oregon harness and requests
us.amazon.ergo-1.0. If either differs in your copy, compare the source Region with the AgentCore announcement and the profile spelling with the model card. For authorization review, take the destination list from the profile in the source Region. A 404 warrants checking the harness ID and Region before troubleshooting Bedrock. For a related example of profile scope in a Bedrock integration, see Kimi Code CLI on Amazon Bedrock · AWS announcement · Amazon Ergo model card - Restart the experiment after ambiguous delivery. If the stream disconnects after text arrives, or the parser shows a missing or abnormal stop reason, treat that run as incomplete. The service may have processed the request before your client lost the response. Replaying on the same ID could add another message to the history you were trying to measure. After addressing the cause, run the script again from the beginning. It generates a new actor and two new session IDs before sending any prompts. The documented stop reasons can help explain symptoms such as an output limit (
max_tokens) or a time limit (timeout_exceeded). AWS streaming response guide - Return a caller to its usual model by dropping the override field. Follow the third-turn call shape in the script. Removing the key restores default selection on a new request under the API contract. For a conversation you want to continue after a complete response, reuse its session ID. For a measurement whose stream failed ambiguously, start with a fresh ID. Any synthetic conversation events follow the sandbox’s memory settings, so a fresh session changes the test’s starting point while stored data follows its configured retention. Models and instructions · Harness memory
If the first Ergo call fails and you need to isolate the default path, use the invoke helper with a fresh UUID for the session, a fresh actor ID and the third turn’s acknowledgment prompt, leaving the optional model argument out. A normal default-only reply narrows your investigation to differences introduced by the Ergo path, such as profile selection or execution-role access. If the default-only call fails at the same point, investigate the shared harness path first. Keep that diagnostic session separate from both sessions used for the recall comparison. InvokeHarness API · Harness security
When a stream ends normally but the assertion fails, save the returned text before retrying. For example, UNKNOWN in the main session points you toward history and request construction, while a full sentence containing the correct values points you toward response formatting. Inspect the system instructions for any requirement to answer in full sentences before changing the recall prompt. If you change the prompt, send that revised wording in both arms and rerun from fresh IDs, so you can still interpret the difference between the two replies.
The run passes when the control says UNKNOWN, the seed acknowledgment matches, the seeded reply matches the fixture, the default turn completes with the expected reply, and the two reads agree on the effective model and version. When the default model changes intentionally, start with a new baseline and keep the fixture and scoring the same. The answer key belongs to the conversation you supplied, so you can reuse it with a different eligible baseline model.
Sources
- AWS What’s New — Amazon Bedrock AgentCore harness now supports Amazon Ergo
- AgentCore Developer Guide — Models and instructions
- AgentCore Data Plane API — InvokeHarness
- AgentCore Developer Guide — Get started and streaming response format
- AgentCore Control Plane API — GetHarness
- Amazon Bedrock User Guide — Amazon Ergo-1.0 model card
- AgentCore Developer Guide — Security and access controls
- AgentCore Developer Guide — Memory
- Boto3 — get_harness
- AgentCore Developer Guide — Harness versioning and endpoints

