![[Small Tip] Amazon Bedrock AgentCore Code Interpreter can now be easily used as a tool in Strands Agents](https://images.ctfassets.net/ct0aopd36mqt/4o8n2qvRpfnsx0yGmKgDZr/1b05f3211bdf64deb5322bf5be42b202/StrandsAgents.png?w=3840&fm=webp)
[Small Tip] Amazon Bedrock AgentCore Code Interpreter can now be easily used as a tool in Strands Agents
This page has been translated by machine translation. View original
Introduction
Hello, I am Kanno from the consulting department, and I love supermarkets.
2026 has started, and I hope to produce even more output this year than last year!
Getting right to the point, are you using AgentCore Built-in tools' Code Interpreter?
I haven't touched it much since writing the article below.
While the code from that time made using Code Interpreter quite simple, there were some cumbersome aspects like session handling. Now it has become even easier to use as it's provided as a built-in tool in Strands Agents. I'd like to introduce this point today!
How It Has Been Simplified
Looking at the official sample, it works with the code below. I've changed the sample code to Japanese.
It's extremely simple...
from strands import Agent
from strands.models import BedrockModel
from strands_tools.code_interpreter import AgentCoreCodeInterpreter
# Initialize Code Interpreter tool
code_interpreter_tool = AgentCoreCodeInterpreter(region="us-west-2")
# Define agent system prompt
SYSTEM_PROMPT = """You are an AI assistant that verifies answers through code execution.
When asked about code, algorithms, or calculations, please write Python code to verify your answers."""
model = BedrockModel(
model_id="us.anthropic.claude-haiku-4-5-20251001-v1:0",
region_name="us-west-2"
)
# Create an agent with Code Interpreter tool
agent = Agent(
tools=[code_interpreter_tool.code_interpreter],
system_prompt=SYSTEM_PROMPT,
model=model
)
# Test the agent with a sample prompt
prompt = "Calculate the first 10 Fibonacci numbers."
print(f"\n\nPrompt: {prompt}\n\n")
agent(prompt)
When executed, it returns results like below. Code Interpreter is used as a tool.
uv run main.py
Prompt: Calculate the first 10 Fibonacci numbers.
I will calculate the first 10 Fibonacci numbers.
Tool #1: code_interpreter
Completed! The **first 10 Fibonacci numbers** are as follows:
| Number | Value |
|------|-----|
| F(1) | 0 |
| F(2) | 1 |
| F(3) | 1 |
| F(4) | 2 |
| F(5) | 3 |
| F(6) | 5 |
| F(7) | 8 |
| F(8) | 13 |
| F(9) | 21 |
| F(10) | 34 |
**About the Fibonacci sequence:**
- It's a sequence where the first two numbers are 0 and 1, and each subsequent number is the sum of the two preceding ones
- Generally defined by the relation F(n) = F(n-1) + F(n-2)
- It has interesting mathematical properties found in various natural phenomena (flower petal arrangements, shell spirals, etc.)
In this sample example, it's somewhat ambiguous whether the generative AI thought of the answer itself or if the tool worked.
So today, I'll create a simple sample comparing cases with and without Code Interpreter to verify that Code Interpreter is working.
Let's Try It Out
Prerequisites
I conducted this verification with the following versions:
| Item | Version |
|---|---|
| Python | 3.12 |
| uv | 0.6.12 |
| strands-agents | 1.20.0 |
| strands-agents-tools | 0.2.18 |
Setup
This time, we'll use uv for setup.
uv init strands-agents-builtin-tools
cd strands-agents-builtin-tools
Once the project is created, add the necessary packages.
uv add strands-agents strands-agents-tools
Setup is now complete!
Comparison Between Not Using Tools and Using Code Interpreter
Let's ask for the current date and time.
Without using tools, the AI can't obtain the real-time time, but with Code Interpreter, we expect it to retrieve and return the current time using Python. We'll use the us.anthropic.claude-sonnet-4-5-20250929-v1:0 model.
from strands import Agent
from strands.models import BedrockModel
from strands_tools.code_interpreter import AgentCoreCodeInterpreter
# Model configuration
model = BedrockModel(
model_id="us.anthropic.claude-sonnet-4-5-20250929-v1:0",
region_name="us-west-2"
)
# Question
prompt = "Please tell me the current date and time (year, month, day, hour, minute, second)."
print("=" * 50)
print("【Comparison】Generative AI Only vs Code Interpreter")
print("=" * 50)
print(f"\nQuestion: {prompt}\n")
# 1. Answer with generative AI only
print("-" * 50)
print("① Answer with generative AI only")
print("-" * 50)
agent_without_tool = Agent(model=model)
response1 = agent_without_tool(prompt)
# 2. Answer using Code Interpreter
print("\n" + "-" * 50)
print("② Answer using Code Interpreter")
print("-" * 50)
code_interpreter = AgentCoreCodeInterpreter(region="us-west-2")
agent_with_tool = Agent(
model=model,
tools=[code_interpreter.code_interpreter],
system_prompt="Please use Code Interpreter to execute code for problems that require retrieving the date and time."
)
response2 = agent_with_tool(prompt)
As for how to use the tool, simply instantiate AgentCoreCodeInterpreter and pass the code_interpreter method as a tool. That's all it takes for integration. Very simple...
Then we include instructions to use Code Interpreter in the system prompt.
For reference, let's also show the code introduced in the previous article for comparison. (Since the processing content is different, please focus only on the session part.)
Previous code example (using code_session)
from bedrock_agentcore.tools.code_interpreter_client import code_session
@tool
def execute_python(code: str, description: str = "") -> str:
"""Execute Python code"""
if description:
code = f"# {description}\n{code}"
img_code = f"""
import matplotlib
matplotlib.use('Agg')
{code}
import matplotlib.pyplot as plt,base64,io,json
imgs=[]
for i in plt.get_fignums():
b=io.BytesIO()
plt.figure(i).savefig(b,format='png')
b.seek(0)
imgs.append({{'i':i,'d':base64.b64encode(b.read()).decode()}})
if imgs:print('_IMG_'+json.dumps(imgs)+'_END_')
"""
try:
with code_session("us-west-2") as code_client:
response = code_client.invoke("executeCode", {
"code": img_code,
"language": "python",
"clearContext": False
})
result = None
for event in response["stream"]:
result = event["result"]
# Process results...
return json.dumps(result, ensure_ascii=False)
except Exception as e:
return json.dumps({"isError": True, "error": str(e)})
Previously, we needed to manage sessions with code_session and execute code with invoke.
Using AgentCoreCodeInterpreter now, session management is automated just by passing it as a tool, making it much simpler.
Execution
uv run main.py
==================================================
【Comparison】Generative AI Only vs Code Interpreter
==================================================
Question: Please tell me the current date and time (year, month, day, hour, minute, second).
--------------------------------------------------
① Answer with generative AI only
--------------------------------------------------
I apologize, but I don't have a real-time clock function, so I cannot tell you the current exact date and time.
To check the current date and time:
- Please check the clock on your device (smartphone, computer, etc.)
- Use voice assistants like "OK Google, what time is it?" or "Hey Siri, what day is today?"
- Search for "current time" on the internet
I apologize for not being able to assist you with this.
--------------------------------------------------
② Answer using Code Interpreter
--------------------------------------------------
Tool #1: code_interpreter
The current date and time is **January 02, 2026 14:43:22**.
While the generative AI alone responded that it couldn't provide the answer, using Code Interpreter allowed it to retrieve the actual current time! It's great that Code Interpreter has become simpler to use. (As a minor detail, the time is displayed in UTC format, which is 9 hours behind Japan time; in Japan it would be 23:00.)
Conclusion
Compared to the method introduced in the previous article, it's nice that the session management part has been simplified and can now be used as a tool!
Since it's so simple to use, I'm inclined to use Strands Agents for tasks that require Code Interpreter.
I hope this article was helpful to you.
Thank you for reading until the end!
Additional Note
As a supplementary note, I wrote almost the same code for AgentCore, deployed it, and checked the logs from the GenAI Observability dashboard. I confirmed that the code was generated as intended and the execution results were returned.
Deployed Code
from bedrock_agentcore.runtime import BedrockAgentCoreApp
from strands import Agent
from strands.models import BedrockModel
from strands_tools.code_interpreter import AgentCoreCodeInterpreter
app = BedrockAgentCoreApp()
@app.entrypoint
def main(payload):
# Get prompt from payload
prompt = payload.get("prompt", "Please tell me the current date and time (year, month, day, hour, minute, second).")
# Model configuration
model = BedrockModel(
model_id="us.anthropic.claude-sonnet-4-5-20250929-v1:0",
region_name="us-west-2"
)
print("=" * 50)
print("【Comparison】Generative AI Only vs Code Interpreter")
print("=" * 50)
print(f"\nQuestion: {prompt}\n")
# 1. Answer with generative AI only
print("-" * 50)
print("① Answer with generative AI only")
print("-" * 50)
agent_without_tool = Agent(model=model)
response1 = agent_without_tool(prompt)
# 2. Answer using Code Interpreter
print("\n" + "-" * 50)
print("② Answer using Code Interpreter")
print("-" * 50)
code_interpreter = AgentCoreCodeInterpreter(region="us-west-2")
agent_with_tool = Agent(
model=model,
tools=[code_interpreter.code_interpreter],
system_prompt="Please use Code Interpreter to execute code for problems that require retrieving the date and time."
)
response2 = agent_with_tool(prompt)
return response2
if __name__ == "__main__":
app.run()
Logs
{
"resource": {
"attributes": {
"deployment.environment.name": "bedrock-agentcore:default",
"aws.local.service": "********.DEFAULT",
"service.name": "********.DEFAULT",
"cloud.region": "us-west-2",
"aws.log.stream.names": "otel-rt-logs",
"telemetry.sdk.name": "opentelemetry",
"aws.service.type": "gen_ai_agent",
"telemetry.sdk.language": "python",
"cloud.provider": "aws",
"cloud.resource_id": "arn:aws:bedrock-agentcore:us-west-2:************:runtime/********/runtime-endpoint/DEFAULT:DEFAULT",
"aws.log.group.names": "/aws/bedrock-agentcore/runtimes/********-DEFAULT",
"telemetry.sdk.version": "1.33.1",
"cloud.platform": "aws_bedrock_agentcore",
"telemetry.auto.version": "0.12.2-aws"
}
},
"scope": {
"name": "strands.telemetry.tracer"
},
"timeUnixNano": 1767407718077295383,
"observedTimeUnixNano": 1767407718077538699,
"severityNumber": 9,
"severityText": "",
"body": {
"output": {
"messages": [
{
"content": {
"message": "[{\"text\": \"[{'type': 'text', 'text': 'Current date and time: 2026-01-03 11:35:18\\\\n\\\\nISO format: 2026-01-03T11:35:18.050048+09:00'}]\"}]",
"id": "tooluse_****************"
},
"role": "assistant"
}
]
},
"input": {
"messages": [
{
"content": {
"content": "{\"code_interpreter_input\": {\"action\": {\"type\": \"executeCode\", \"code\": \"from datetime import datetime\\nimport pytz\\n\\n# Get current date and time in Japan Standard Time (JST)\\njst = pytz.timezone('Asia/Tokyo')\\nnow = datetime.now(jst)\\n\\n# Format and display\\nprint(f\\\"Current date and time: {now.strftime('%Y-%m-%d %H:%M:%S')}\\\")\\nprint(f\\\"\\\\nISO format: {now.isoformat()}\\\")\", \"language\": \"python\"}}}",
"role": "tool",
"id": "tooluse_****************"
},
"role": "tool"
}
]
}
},
"attributes": {
"event.name": "strands.telemetry.tracer",
"session.id": "********-****-****-****-************"
},
"flags": 1,
"traceId": "********************************",
"spanId": "****************"
}

