Repository navigation
Best practice for preventing tool exceptions from leaking to the LLM ? #3311
Replies: 3 comments
|
Yes—this is the default behavior in 1.45.0, so the concern is valid. A decorated I would handle it at two code boundaries: catch expected AWS errors inside the import logging
from typing import Any
import boto3
from botocore.exceptions import ClientError
from strands import Agent, tool
from strands.hooks import AfterToolCallEvent, HookOrder
logger = logging.getLogger(__name__)
SAFE_TOOL_ERROR = "The knowledge base is temporarily unavailable."
@tool
def search_knowledge_base(query: str) -> str | dict[str, Any]:
"""Search the knowledge base using the given query."""
client = boto3.client("bedrock-agent-runtime", region_name=_REGION)
try:
response = client.retrieve(
knowledgeBaseId=_KNOWLEDGE_BASE_ID,
retrievalQuery={"text": query},
)
except ClientError:
# Do not interpolate the exception or its response, and do not attach
# exc_info or a traceback.
logger.warning("knowledge base retrieve failed")
return {
"status": "error",
"content": [{"text": SAFE_TOOL_ERROR}],
}
chunks = [
item["content"]["text"]
for item in response["retrievalResults"]
if item.get("content", {}).get("text")
]
return "\n\n".join(chunks)
def sanitize_tool_error(event: AfterToolCallEvent) -> None:
"""Make every model-visible tool failure generic."""
if event.exception is None and event.result.get("status") != "error":
return
event.result = {
"toolUseId": event.result["toolUseId"],
"status": "error",
"content": [{"text": SAFE_TOOL_ERROR}],
}
agent = Agent(
model=bedrock_model,
session_manager=session_manager,
tools=[search_knowledge_base],
system_prompt=_SYSTEM_PROMPT,
callback_handler=None,
)
# SDK_LAST runs after lower-priority groups. Keep this callback alone at that
# priority: same-priority AfterToolCallEvent callbacks run newest-first.
agent.add_hook(
sanitize_tool_error,
AfterToolCallEvent,
order=HookOrder.SDK_LAST,
)Returning The decorator and executor catch A few security details are important:
If the model cannot usefully recover, an even stricter option is to re-raise |
|
Thanks for the suggestions and advice! Thank you. |
|
There is no setting that stops the SDK from handing exception text to the model. In DecoratedFunctionTool.stream (strands-py/src/strands/tools/decorator.py), any exception that escapes the tool is caught and turned into a tool result whose content is "Error: {ExceptionType} - {str(exception)}", and that string is what the model sees on the next turn. Catch the error inside the tool, log the real exception on the server, and return a short generic sentence such as "The knowledge base search failed. Try again later." If a tool you do not control still emits boto text, an AfterToolCallEvent hook can replace it. That event marks result as writable, so the callback can swap the content blocks for a generic message before the result is stored in the conversation. A system prompt only asks the model not to repeat the text. It does not remove the text from the tool result. |
Uh oh!
There was an error while loading. Please reload this page.
I'm experiencing the following issue with the Lambda function below.
If the Lambda execution role is missing the required IAM permissions, the AI agent may expose infrastructure-related information, such as AWS ARNs, in its response.
While the immediate issue can be resolved by granting the Lambda execution role the appropriate permissions, my primary concern is that runtime errors from the Lambda function are being passed through to the LLM and included in the agent's response.
From a security perspective, I'm concerned that exposing raw runtime exceptions to the LLM could inadvertently leak infrastructure-related information.
I understand that this could potentially be mitigated with a system prompt or guardrails. However, I'm wondering if there is a recommended way to prevent program errors from ever being exposed to the LLM in the first place. In other words, is there a best practice for handling these exceptions in code so that the LLM never receives the raw error message?
Test prompt
Agent response (partially redacted)
Lambda code (partially redacted)
Versions
All reactions