Skip to main content













Building observable AI agents with Amazon Bedrock and W&B Weave
A complete guide to creating customer support agents with full traceability, systematic evaluation, and production-ready architecture.
Last updated: March 24, 2026
Imagine deploying a customer support agent to production. A customer asks, "I want to return order ORD-2024-001." The agent responds, "Your return has been processed."
Everything looks fine. But the customer emails back, confused because no return was actually created. What went wrong?
Here's the frustrating reality: we have no way to find out. Did the agent check if the order exists? Did it verify return eligibility? Did the return function execute? Did it fail silently?
Traditional logging shows "Request received" and "Request completed" but nothing about what happened in between. The agent is a black box. We see inputs and outputs, but not the reasoning that connects them.
Fixing this issue is fundamentally different from debugging regular software. In traditional code, we set breakpoints, step through execution line by line, and inspect variables at each step. With AI agents, decision-making happens inside the language model, which we cannot see. The model decides which functions to call, extracts parameters from natural language, orchestrates multiple steps, and synthesizes results. All of this reasoning is invisible.
The cost of this invisibility is high. When production agents fail, we can't replay what happened. We can't see which step broke. We waste hours trying to reproduce the issue, guessing at root causes, and deploying speculative fixes. Meanwhile, customers are frustrated, and support tickets pile up.
This tutorial solves that problem.
We'll build an AI agent where every decision is visible, every function call is traced, and every result is logged. When something goes wrong, we'll see exactly what happened and why. No guessing. No reproduction attempts. Just direct inspection of the complete execution path.
We'll use three technologies working together:
- Amazon Bedrock provides AI infrastructure without requiring server management or model weights.
- Function calling makes agents useful by enabling them to execute real operations rather than just talk about them.
By the end, we'll have a complete customer support agent that handles order status checks, return processing, and FAQ searches with full visibility into every decision it makes.
What do we need?
- An AWS account (free tier works),
- Python 3.9 or later,
- a free W&B account, and
- about 30 minutes.
What will it cost? Less than one cent to complete this entire tutorial.
Let's start by understanding what we need to set up.
What is Amazon Bedrock?
Amazon Bedrock is AWS's fully managed service for accessing foundation models from leading AI companies like Anthropic, Meta, Mistral, Cohere, and Amazon through a single API. Instead of juggling separate API keys for each provider, managing infrastructure for hosting models, or downloading gigabytes of model weights, Bedrock provides a single unified interface. It supports building and deploying generative AI applications, including chatbots, text generation tools, RAG pipelines, and agent creation.
That last one is exactly what we're here for.
Think of it like this: we make an API call describing what we want the model to do. Bedrock handles all the infrastructure behind the scenes. The model processes our request and sends back a response. We never worry about servers, GPUs, or model deployment.
The practical advantages are significant. No infrastructure to manage means we focus on building the agent, not configuring clusters. No model weights to download means we get started immediately. One API for multiple providers means we can switch models by changing a single configuration line.
But there's a catch: Bedrock doesn't give access to models by default. We have to explicitly request it. This security feature ensures accounts have legitimate use cases. The good news: for most models, access is granted instantly.
How do you access Bedrock? (click to expand)
Why are we using Amazon Nova Lite instead of Claude or other models?
This question comes up immediately. Bedrock offers models from Amazon, Anthropic, Meta, and others. Why specifically Nova Lite?
Three practical reasons drive this choice.
- Rate limits matter during development. Nova Lite allows 20 requests per minute. Claude allows 2 requests per minute. When we're testing and debugging, we'll make many API calls. The 10x higher limit means we won't constantly hit throttling errors that slow down development.
- Cost matters for learning. Nova Lite costs about 4 times less than Claude. For a tutorial where we'll make dozens of test requests, the savings add up.
- Capability matches our needs. For function-calling tasks like customer support, Nova Lite performs just as well as more expensive models. Both understand tool definitions and extract parameters from natural language effectively.
We can always add Claude access later if we want. The code works with either model by changing one configuration line. For now, Nova Lite is the practical choice for learning and development.
How to test if Amazon Bedrock access is actually working?
Before writing any code, let's verify the setup in Bedrock's playground. Click "Playgrounds" in the left sidebar, then "Chat." Select Nova Lite from the model dropdown.
Type a test message: "Hello! How can I help with customer orders?"
If we see a response from the model, access is working correctly. The playground is useful for quick tests, but we're about to build something much more powerful with code.

Bedrock Playground Interface
The Bedrock Playground provides a no-code interface to test models—select Nova Lite from the dropdown to verify your access before writing any code.
💡
One important note: if we test Claude in the playground later, we won't see a "Tools" or "Functions" option in the interface. This is misleading. Claude absolutely supports function calling through the API. The playground UI just doesn't expose that feature. Don't let this confuse us when we start coding.
Now that Bedrock access is confirmed, we need to understand the rate limit constraints we'll be working within.
What are the rate limits, and how do they affect my agent?
A point that catches many developers off guard is that AWS Bedrock enforces strict rate limits on API calls. If we make requests too quickly, AWS rejects them with ThrottlingException errors. Our agent stops working until we slow down.
Rate limits are per minute, per model, per AWS account. They apply regardless of where the code runs. Running locally versus running on an AWS server makes no difference. The account determines the limit.
How to find out what your rate limits are?
Search for "Service Quotas" in the AWS Console. Select the Service Quotas service. Click "AWS services" in the left sidebar. Find "Amazon Bedrock" and click it. Search for "requests per minute."

Service Quotas Search
Navigate to Service Quotas through the AWS Console search to check your rate limits—this determines how many API requests you can make per minute.

Service Quotas Dashboard
The Service Quotas dashboard lets you view and manage API limits across all AWS services—select 'AWS services' to find Bedrock-specific quotas.

Amazon Bedrock in Service List
Locate Amazon Bedrock in the services list to view model-specific rate limits that will constrain how quickly your agent can process customer requests.

Bedrock Rate Limits
This quota list shows Nova Lite allows 20 requests per minute while Claude allows only 2—this 10x difference directly impacts development speed and testing efficiency.
We'll see quotas for different models. The critical ones for us:
- Amazon Nova Lite: 20 requests per minute
- Anthropic Claude 3.5 Sonnet: 2 requests per minute
Why do these numbers actually matter?
Consider what happens when a customer asks a question. Our agent makes multiple API calls per interaction.
- First call: decide which tool to use.
- Second call: synthesize results into a response.
That's 2 requests for one customer question.
With Nova Lite's 20 requests-per-minute limit, we can handle about 10 customer conversations per minute during development. With Claude's 2 requests-per-minute limit, we could only handle 1 conversation per minute. This is another practical reason why we chose Nova Lite.
But rate limits aren't just a development inconvenience. They directly affect how we structure our code. We'll need to add delays between API calls to stay under the limit. We'll need retry logic for when we accidentally exceed it. We'll need to plan request patterns carefully.
The good news: for production deployments, we can request higher quotas.
Can you increase these limits for production?
Yes, and it's straightforward. Go to Service Quotas, find the specific quota for our model, click "Request increase," specify the desired limit (like 100 requests per minute), explain the business use case, and submit.

Request Quota Increase
To scale beyond default limits, click 'Request increase at account level' for any quota, AWS typically approves production increases within 24-48 hours at no additional cost. There's no additional cost. We still only pay per actual request made. The higher quota just removes the artificial limit.
With 100 requests per minute, our agent could comfortably handle 30 to 40 concurrent customer conversations. At even larger scales, quotas can reach the thousands.
Our tutorial code will include delays to stay under the default limits. This is good practice anyway since it prevents unexpected costs from runaway loops or bugs that spam the API.
Now that we understand rate limits, we need credentials to actually make API calls.
Note: This rate limit depends on your country and region; some regions may not have access to increase it
How to set up credentials securely?
We need AWS credentials to call Bedrock from our local machine. But using root account credentials is dangerous. If those leak (committed to GitHub, logged to a file, stolen from a laptop), someone could access everything in our AWS account and potentially rack up massive charges.
The secure approach: create a dedicated IAM user with limited permissions. This user can only access Bedrock, nothing else. If credentials leak, the damage is contained to Bedrock API calls.
What exactly is an IAM user, and why use one?
IAM (Identity and Access Management) lets us create users with specific permissions. Instead of giving our application full account access, we give it just enough permission to do its job.
Think of it like giving a house key to a dog walker. We don't give them the key to our safe, our car, or our filing cabinet. Just the front door key. If they lose it, the damage is limited.
For our agent, we create a user who can only call Bedrock APIs. Nothing else. No access to databases, no access to billing, no access to other AWS services.
How to create an IAM user?
Search for "IAM" in the AWS Console. Click "Users" in the left sidebar. Click "Create user."

IAM User Creation
Create a dedicated IAM user with only Bedrock permissions rather than using root credentials; this limits potential damage if credentials are accidentally exposed.
Set username to bedrock-tutorial. Click "Next."
On the permissions page:
- select "Attach policies directly."
- Search for "Bedrock."
- Check the box next to AmazonBedrockFullAccess. This grants access only to Bedrock operations.
- Click "Next", then "Create user."
Now we generate credentials.
- Click on the newly created user.
- Go to the "Security credentials" tab.
- Scroll to "Access keys" and
- Click "Create access key."
- Select "Application running outside AWS" as the use case, then
- Click "Next", then "Create access key."
Critical step: Download the CSV file. This contains the access key ID and secret access key. The secret is only shown once. If we lose it, we'll have to delete this key and create a new one.
The CSV looks like:
Access key ID,Secret access key
Keep this file secure. Store it somewhere safe. Never commit it to version control. We'll use these credentials in the next step.
How to connect your code to Amazon Bedrock?
Now we set up the project on our local machine, configure credentials securely, and verify the connection works
What project structure do you need?
Create a new directory and set up a Python virtual environment:
mkdir bedrock-weave-tutorialcd bedrock-weave-tutorialpython -m venv venvsource venv/bin/activate # Windows: venv\Scripts\activate
Install the required packages:
pip install boto3 weave python-dotenv pandas
Each package serves a specific purpose. boto3 is AWS's Python SDK for making API calls. Weave provides automatic observability. python-dotenv manages credentials securely. pandas helps us work with CSV data.
How to store credentials without hardcoding them?
Create a file named .env in the project root:
AWS_REGION=eu-north-1 AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY WANDB_API_KEY=your_wandb_key_here DATA_SOURCE=csv
Replace the AWS credentials with actual values from the CSV file we downloaded. Get the W&B API key from https://wandb.ai/settings.
Never commit the .env file to version control. Create a .gitignore file immediately:
.envvenv/__pycache__/*.pyc
This approach keeps credentials out of our code. We can share the code publicly without exposing sensitive information.
How to verify that the connection with Amazon Bedrock works?
Create test_connection.py:
import boto3import osfrom dotenv import load_dotenvload_dotenv()bedrock = boto3.client('bedrock-runtime',region_name=os.getenv('AWS_REGION'))response = bedrock.converse(modelId='amazon.nova-lite-v1:0',messages=[{'role': 'user','content': [{'text': 'Hello!'}]}])print(" Connection successful!")print(f"Response: {response['output']['message']['content'][0]['text']}")
Run it:
python test_connection.py
If we see a success message and a response from the model, everything is configured correctly. This confirms credentials work, region is set correctly, model access is active, and boto3 can communicate with Bedrock.
If there's an error, check that the credentials in .env match the CSV , confirm the region is correct, verify Nova Lite access was granted, and ensure boto3 is installed successfully.
Our Amazon Bedrock tutorial
Before building the agent, we need to understand how AI models do useful work beyond generating text. This is crucial because it fundamentally changes what agents can accomplish.
What happens if your agent can't call functions?
Without function calling, an AI model can only generate text. Ask it to check an order status, and it might respond, "I would query the database for order ORD-2024-001 and look up the shipping information." But it cannot actually query anything. It's describing hypothetical actions, not performing real ones.
This limitation makes the agent essentially useless for real work. It can have convincing conversations about what it would do, but it cannot actually do anything. It's like hiring an employee who only writes memos about work, not actually doing the work.
So, what does function calling enable?
Function calling enables the model to execute real Python functions. We define a set of tools (functions) that the model can use. Each tool has a name, description, and a schema that defines its parameters.
When processing a user request, the model can request to execute these tools. Here's the flow:
- User asks "What's the status of order ORD-2024-001?"
- The model reads this and recognizes it needs information from our order system.
- The model requests to call the check_order_status tool with the parameter order_id="ORD-2024-001".
- We execute the Python function that queries our database.
- The function returns order details.
- We send those details back to the model.
- The model synthesizes the data into a natural language response.
This transforms the agent from a text generator into a system that takes real actions. It can query databases, create records, send emails, call APIs, or perform any other operation we define as a tool.
Can the model use multiple tools?
Yes, and this is where agents become genuinely powerful. The model can orchestrate complex workflows by chaining tools together based on what each step reveals.
If a user asks "Can I return my order?", the model might first call check_order_status to get order details, analyze those details to determine return eligibility based on purchase date and item type, then call process_return if the order qualifies. It automatically determines this multi-step workflow based on its understanding of the goal and available tools.
We don't write explicit workflow logic saying "first check status, then check eligibility, then process return." The model figures out the sequence based on function descriptions and the current situation. This flexibility lets it handle requests we never explicitly programmed for.
What tools will our customer support agent need?
Our agent needs three core capabilities:
- check_order_status looks up order details by ID. It tells us if an order exists, its current status (processing, shipped, delivered), what items it contains, and tracking information.
- process_return initiates a return for an order. It checks eligibility (is it within 30 days? is the item returnable?), creates the return record, and provides return instructions to the customer.
- search_faq finds answers in a knowledge base. It handles common questions about policies, shipping times, and procedures without needing custom code for each question type.
These three tools cover the most common customer support scenarios. In production, we'd add more: order cancellation, address updates, discount application, order modification, and so on. But these three are enough to demonstrate the complete pattern.
Now that we understand what we're building, let's look at the sample data we'll work with.
What sample data do I need to make this work?
Before coding the agent, we need sample data representing customer orders. This data lets us test different scenarios without connecting to a real database.
Create a data directory in the project root. Inside it, create sample_orders.csv:
order_id,customer_name,items,status,total,order_date,return_eligible,tracking_numberORD-2024-001,Sarah Johnson,Wireless Headphones,delivered,129.99,2024-11-15,True,TRK1234567890ORD-2024-002,Mike Chen,Laptop,shipped,899.99,2024-12-01,True,TRK0987654321ORD-2024-003,Emma Davis,Running Shoes,processing,79.99,2024-12-05,False,ORD-2024-004,James Wilson,Coffee Maker,delivered,149.99,2024-10-15,False,TRK1122334455ORD-2024-005,Lisa Brown,Bluetooth Speaker,delivered,59.99,2024-11-20,True,TRK5544332211
Why this specific data structure?
Notice the variety here. This is intentional.
- Order ORD-2024-001 has been delivered and is eligible for returns. Perfect for testing the happy path.
- Order ORD-2024-002 is still shipping. Tests how the agent communicates in-progress status.
- Order ORD-2024-003 is processing and not eligible for returns. Tests how the agent handles ineligible return requests.
- Order ORD-2024-004 was delivered months ago and is outside the return window. Tests another type of ineligible return.
- Order ORD-2024-005 is recent and eligible. Provides another successful return scenario.
This diversity helps us test edge cases, error scenarios, and different conversation flows without needing hundreds of records. In production, this data would come from a real database or API. For learning, CSV is simpler while teaching the same concepts.
Now we can start building the actual tools.
How to build tools that W&B Weave can automatically trace?
The tools are Python functions that do real work: querying data, processing returns, searching FAQs. But we want every call to these functions automatically traced for observability. That's where Weave comes in.
Create src/tools.py:
import weavefrom typing import Dictimport pandas as pdFAQS = [{"question": "return policy","answer": "We accept returns within 30 days of delivery. ""Items must be unused in original packaging."},{"question": "shipping time","answer": "Standard shipping takes 5 to 7 business days. ""Express takes 2 to 3 business days."}]@weave.op()def check_order_status(order_id: str) -> Dict:"""Check the status of a customer order"""orders_df = pd.read_csv('data/sample_orders.csv')order = orders_df[orders_df['order_id'] == order_id]if order.empty:return {"success": False, "error": f"Order {order_id} not found"}order_data = order.iloc[0]return {"success": True,"order_id": order_id,"status": order_data["status"],"customer_name": order_data["customer_name"],"items": order_data["items"],"total": float(order_data["total"]),"tracking_number": order_data.get("tracking_number", "Not assigned")}@weave.op()def process_return(order_id: str, reason: str = "customer request") -> Dict:"""Process a return request"""orders_df = pd.read_csv('data/sample_orders.csv')order = orders_df[orders_df['order_id'] == order_id]if order.empty:return {"success": False, "error": f"Order {order_id} not found"}order_data = order.iloc[0]if not order_data.get("return_eligible"):return {"success": False, "error": "Order not eligible for return"}return_id = f"RET-{hash(order_id) % 10000}"return {"success": True,"return_id": return_id,"refund_amount": float(order_data["total"]),"instructions": "Shipping label emailed within 24 hours"}@weave.op()def search_faq(query: str) -> Dict:"""Search FAQ knowledge base"""query_lower = query.lower()results = [faq for faq in FAQSif any(word in query_lower for word in faq['question'].split())]if not results:return {"success": False, "message": "No FAQ found"}return {"success": True, "results": results, "count": len(results)}
What does the @weave.op() decorator do?
This single line is the key to observability. The @weave.op() decorator tells Weave to automatically trace this function. Without writing any logging code ourselves, Weave will capture when the function is called, what parameters it receives, what it returns, how long it takes, and which other function calls it.
This automatic instrumentation is transformative. In traditional development, we'd write logging statements manually: log the input, intermediate steps, and output, log timing information, and add correlation IDs to connect related logs. That's dozens of lines of boilerplate code per function.
With Weave, we add one decorator and get all of that automatically. The function code stays clean and focused on business logic. Observability comes for free.
Why return dictionaries with a success field?
Notice every function returns a dictionary with a "success" field. This consistent structure makes it easy for the model to understand results.
When check_order_status succeeds, it returns {"success": True, "order_id": "...", "status": "...", ...}. When it fails, it returns {"success": False, "error": "Order not found"}. The model can check the success field to determine what happened and respond appropriately.
Here's what that looks like in practice: Weave captures the exact dictionary your tool returns in real time:

Screenshot: check_order_status trace output
Weave captures the full output dictionary from check_order_status — success: true, order ID, customer name, status, items, and tracking number. This is exactly what the model reads to formulate its response.
This pattern also makes error handling clean. We don't throw exceptions that crash the agent. We return error information that the model can communicate to the customer in a friendly way.
Now we have the tools. Next, we need to build the agent that uses them.
How Does the Agent Actually Orchestrate Everything?
The agent is the conductor. It receives user messages, decides which tools to use, executes those tools, and synthesizes results into responses. Let's build it step by step.
Create src/agent.py:
import weaveimport boto3import timefrom typing import List, Dictfrom botocore.exceptions import ClientErrorfrom src.tools import check_order_status, process_return, search_faqclass CustomerSupportAgent:"""Customer support agent with complete observability"""def __init__(self):self.bedrock = boto3.client('bedrock-runtime', region_name='eu-north-1')self.model_id = 'amazon.nova-lite-v1:0'self.tools = self._define_tools()self.tool_functions = {"check_order_status": check_order_status,"process_return": process_return,"search_faq": search_faq}def _define_tools(self) -> List[Dict]:"""Define tools in Bedrock's format"""return [{"toolSpec": {"name": "check_order_status","description": "Check order status, tracking, and delivery information","inputSchema": {"json": {"type": "object","properties": {"order_id": {"type": "string","description": "Order ID like ORD-2024-001"}},"required": ["order_id"]}}}},{"toolSpec": {"name": "process_return","description": "Process return request for an order","inputSchema": {"json": {"type": "object","properties": {"order_id": {"type": "string"},"reason": {"type": "string"}},"required": ["order_id"]}}}},{"toolSpec": {"name": "search_faq","description": "Search FAQ for policies and information","inputSchema": {"json": {"type": "object","properties": {"query": {"type": "string"}},"required": ["query"]}}}}]@weave.op()def _call_bedrock(self, messages: List[Dict]) -> Dict:"""Call Bedrock with rate limiting"""time.sleep(9) # Stay under 20 requests per minutetry:return self.bedrock.converse(modelId=self.model_id,messages=messages,toolConfig={"tools": self.tools})except ClientError as e:if e.response['Error']['Code'] == 'ThrottlingException':time.sleep(20)return self._call_bedrock(messages)raise@weave.op()def chat(self, user_message: str) -> Dict:"""Handle customer message with tool orchestration"""messages = [{"role": "user", "content": [{"text": user_message}]}]tools_used = []turn_count = 0while turn_count < 10:turn_count += 1response = self._call_bedrock(messages)if response['stopReason'] == 'end_turn':final_text = "".join(c['text'] for c in response['output']['message']['content']if 'text' in c)return {'response': final_text,'tools_used': tools_used,'turns': turn_count}elif response['stopReason'] == 'tool_use':assistant_message = response['output']['message']messages.append(assistant_message)tool_results = []for content in assistant_message['content']:if 'toolUse' in content:tool_use = content['toolUse']tools_used.append(tool_use['name'])tool_function = self.tool_functions[tool_use['name']]result = tool_function(**tool_use['input'])tool_results.append({"toolResult": {"toolUseId": tool_use['toolUseId'],"content": [{"json": result}]}})messages.append({"role": "user", "content": tool_results})return {'response': "Maximum turns reached", 'tools_used': tools_used, 'turns': turn_count}
What's Happening in the chat() Method?
Let me walk through the flow in plain language because this is where the magic happens.
/Step 1: We start with the user's message. This becomes the first message in our conversation with Bedrock.
Step 2: We call Bedrock and wait for its response. Bedrock will either say "I have a final answer" or "I need to use these tools."
Step 3a: If Bedrock has a final answer, we extract the text and return it to the user. Done.
Step 3b: If Bedrock wants to use tools, we look at which tools it requested and with what parameters. We execute those actual Python functions. We package the results and send them back to Bedrock. Then we loop back to Step 2.
This loop continues until Bedrock provides a final answer or we hit the maximum turn limit (10 turns as a safety check).
Why the 9-second delay in _call_bedrock()?
Remember Nova Lite's limit of 20 requests per minute? That's one request every 3 seconds minimum. We use 9 seconds to be extra safe because each customer conversation involves multiple back-and-forth calls. With 9 seconds between calls and typically 2 calls per conversation, we safely handle multiple concurrent conversations without hitting rate limits.
This delay feels slow during development. With higher quotas in production, we'd reduce it significantly. The pattern stays the same, just with different timing.
What's the retry logic for?
Even with delays, we might occasionally hit rate limits during burst scenarios. The retry logic catches ThrottlingException errors, waits 20 seconds, and tries again. This handles edge cases gracefully without crashing the agent.
Now let's actually run this agent and see what happens.
How do I test if my agent is actually working?
Create src/agent_client.py to run some test scenarios:
import weavefrom src.agent import CustomerSupportAgentweave.init("bedrock-customer-support")agent = CustomerSupportAgent()print("\nTesting customer support agent\n" + "="*60)result = agent.chat("What's the status of order ORD-2024-001?")print(f"\n1. Order status check:")print(f"Response: {result['response']}")print(f"Tools used: {result['tools_used']}")print(f"Turns: {result['turns']}")time.sleep(10)result = agent.chat("I want to return order ORD-2024-001")print(f"\n2. Return processing:")print(f"Response: {result['response']}")print(f"Tools used: {result['tools_used']}")print(f"Turns: {result['turns']}")time.sleep(10)result = agent.chat("What's your return policy?")print(f"\n3. FAQ search:")print(f"Response: {result['response']}")print(f"Tools used: {result['tools_used']}")print(f"Turns: {result['turns']}")print("\nAll tests complete. Check Weave dashboard for traces.")
Run it:
python -m src.agent_client
What should I see in the output?
The terminal will show progress as each scenario executes. Due to rate limiting, this takes a couple of minutes total.
The agent processes each scenario. We see that it uses the correct tools for each question. The terminal output confirms everything works. But here's what we don't see yet: what's actually happening inside the agent. Which decisions is the model making? How long does each step take? What happens when something fails? In Part 2, we'll open up the black box completely. We'll examine every trace in Weave, learn how to debug production failures, build a systematic evaluation process, and prepare for real deployment.
Part 2: Deep observability, evaluation, and production deployment
In Part 1, we built a complete customer support agent with Amazon Bedrock and W&B Weave. It handles order status checks, return processing, and FAQ searches. We tested it and confirmed it works.
Now comes the critical part: understanding what's happening inside that agent, debugging it when things go wrong, testing it systematically, and deploying it to production with confidence.
This is where observability transforms from "nice to have" to "essential."
What can I actually see in the Weave dashboard?
Open a browser and go to https://wandb.ai. Log in and navigate to the "bedrock-customer-support" project.

Weave Traces List View
The Weave dashboard displays every agent interaction as a separate row—green checkmarks indicate success, while columns show which tools were called and how many API turns occurred.
What am I looking at here?
Each row represents one complete agent interaction from our test run. Let me decode what we're seeing.
Green checkmarks on the left mean success. Red circles would indicate failures. The user_message column shows what the customer asked. The response column previews the agent's answer. The tool_uses column shows which functions were called. The turns column shows how many exchanges happened with Bedrock.
Look at the return processing row. The tool_uses column shows ["check_order_status", "process_return"]. This tells us something important: the agent called two functions. It didn't blindly try to process a return. It first checked if the order exists, then processed the return. This is intelligent behavior we didn't explicitly program. The model figured out this workflow automatically based on the tool descriptions.
This table view provides a bird's eye view of all agent interactions. In production with real customers, we'd see hundreds or thousands of rows here. We could filter to show only failures, search for specific order IDs, or sort by response time to find slow queries.
But the real power comes from drilling into individual traces.
What happens when I click on a Trace?
Click on the FAQ search scenario. A detailed panel opens.

Detailed Trace View
Clicking any trace reveals the complete execution tree showing exactly what happened: which functions the agent called, what parameters it extracted, and how long each step took.
Now we see exactly what happened, step by step. The left side shows an execution tree. This is the function-call hierarchy.
At the top: run_agent_detailed (19.50 seconds total). Inside that: BedrockAgent.chat (19.50 seconds). Inside that: Two calls to BedrockAgent-call_bedrock (9.66 seconds and 9.82 seconds). Inside the first Bedrock call: search_faq (0ms).
The right panel shows actual data at each step. Under Inputs: the user's message. Under Output: the complete response, the tools used list, turn count, and success status.
Why is this level of detail important?
Because it shows us exactly how the agent made its decision. Traditional logging would tell us "function executed" and "response returned." Weave tells us the model decided to call search_faq with the parameter query "return policy". The function returned FAQ results in less than 1 millisecond, Bedrock spent 9.82 seconds synthesizing those results into natural language, and delivered the answer successfully in 2 conversation turns.
If this trace showed a failure, we'd see exactly which step failed, what data was available when it failed, what error occurred, and what the agent was trying to do. No guessing. No reproduction attempts. Just direct inspection of what actually happened.
Let's look at an example of a failure to see what debugging looks like.
What does debugging look like when something fails?
During development, we encountered rate limit errors. Let's examine one of those failed traces to understand how Weave helps debug.

Failed Trace with Error
When failures occur, Weave traces show precisely where things broke—here, a ThrottlingException on the second Bedrock call reveals a rate limit issue, not a logic error.
What information does a failed Trace give me?
The red circle immediately signals a problem. The error is displayed prominently:
ThrottlingException: Too many requests, please wait before trying again
Now look at the execution tree. Total conversation time: 28.26 seconds. First Bedrock call: succeeded in 12.26 seconds. The check_order_status tool: executed successfully in 1ms. Second Bedrock call: failed after 15.98 seconds.
What does this timeline tell me about what went wrong?
Reading the timeline like a story: The agent received a customer message. It decided to call check_order_status. That function executed successfully and returned order data. The agent tried to make a second API call to Bedrock to synthesize the response. That second call hit the rate limit. The long duration (15.98 seconds) indicates our retry logic kicked in multiple times before eventually failing.
This information is actionable. The problem isn't with our tool functions since check_order_status succeeded. The problem isn't with parameter extraction since the model correctly identified which tool to call. The problem is simply making API calls too quickly.
The solution is clear: increase delays between calls or request higher rate limits from AWS. No guessing required.
How Is This Better Than Traditional Error Messages?
Traditional logging would show:
[INFO] Request received[INFO] Function called[ERROR] Bedrock API error[INFO] Request failed
That tells us almost nothing useful. Which function? What parameters? Which API call failed? What had the agent accomplished before failing?
Weave shows: The exact user input that triggered the failure. Which API call in the sequence failed (second, not first). Complete error message with AWS error code. Timing showing retry attempts. Context that check_order_status had already succeeded. Stack trace pointing to exact code locations.
This is the difference between spending hours reproducing and debugging versus spending minutes examining a trace and deploying a fix.
Now that we understand how to build and debug the agent, we need to test it systematically across many scenarios.
How do I know my agent works across different scenarios?
Manual testing found three working scenarios. But production agents face diverse situations:
- non-existent orders,
- orders outside return windows,
- ambiguous questions, and
- edge cases we haven't thought of.
We need a systematic evaluation that covers this diversity and gives us quantitative confidence that the agent works correctly.
What makes a comprehensive test dataset?
We need test cases representing the range of real customer interactions. Create
src/evaluation.py:
import weaveimport timefrom src.agent import CustomerSupportAgentweave.init("bedrock-customer-support")agent = CustomerSupportAgent()evaluation_dataset = [{'id': 'order_status_normal','category': 'ORDER_STATUS','query': "What's the status of order ORD-2024-001?",'expected_tools': ['check_order_status'],'expected_outcome': 'success'},{'id': 'order_nonexistent','category': 'EDGE_CASES','query': "Check order ORD-9999-999",'expected_tools': ['check_order_status'],'expected_outcome': 'not_found'},{'id': 'return_eligible','category': 'RETURNS','query': "I want to return order ORD-2024-001. It's damaged.",'expected_tools': ['check_order_status', 'process_return'],'expected_outcome': 'return_created'},{'id': 'return_ineligible','category': 'RETURNS','query': "Return order ORD-2024-004",'expected_tools': ['check_order_status', 'process_return'],'expected_outcome': 'return_ineligible'},{'id': 'faq_returns','category': 'FAQ','query': "What's your return policy?",'expected_tools': ['search_faq'],'expected_outcome': 'success'},{'id': 'faq_shipping','category': 'FAQ','query': "How long does shipping take?",'expected_tools': ['search_faq'],'expected_outcome': 'success'},]
Notice the variety. We test normal flows (order status checks), error cases (non-existent orders), edge cases (orders outside the return window), and different phrasings of similar questions. This diversity helps us catch bugs that only appear in specific scenarios.
Each test case includes: an ID for tracking, a category for grouping similar tests, the actual customer query, tools we expect the agent to use, and the outcome we expect (success, not_found, return_ineligible).
How do I measure whether the agent is performing well?
Add evaluation metrics:
@weave.op()def evaluate_tool_selection(output: dict, expected_tools: list) -> dict:"""Did the agent call the right tools?"""tools_called = set(output.get('tools_used', []))tools_expected = set(expected_tools)correct_tools = tools_called & tools_expectedprecision = len(correct_tools) / len(tools_called) if tools_called else 0recall = len(correct_tools) / len(tools_expected) if tools_expected else 0return {'correct': tools_called == tools_expected,'precision': precision,'recall': recall}@weave.op()def evaluate_efficiency(output: dict) -> dict:"""Did it complete efficiently?"""turns = output.get('turns', 0)return {'efficient': turns <= 3, 'turns': turns}@weave.op()def log_evaluation_summary(results: list) -> dict:"""Compute aggregate statistics"""total_tests = len(results)tool_correct = sum(r['tool_evaluation']['correct'] for r in results)efficiency_good = sum(r['efficiency_evaluation']['efficient'] for r in results)return {'model': 'CustomerSupportAgent','total_tests': total_tests,'successful_tests': sum(1 for r in results if r['output'].get('response')),'tool_selection_accuracy': tool_correct / total_tests,'efficiency_score': efficiency_good / total_tests,'overall_score': (tool_correct + efficiency_good) / (total_tests * 2)}
These metrics answer specific questions. Tool selection accuracy: did the agent call the right functions? Efficiency: did it complete tasks quickly without unnecessary steps? We could add more metrics like response quality or error handling, but these two cover the essentials.
How do I run the evaluation?
Add the evaluation runner:
def run_evaluation():print("\nRunning systematic evaluation...")print(f"Dataset: {len(evaluation_dataset)} test cases\n")results = []for test_case in evaluation_dataset:print(f"Testing: {test_case['id']}...")output = agent.chat(test_case['query'])tool_eval = evaluate_tool_selection(output, test_case['expected_tools'])efficiency_eval = evaluate_efficiency(output)results.append({'test_case': test_case,'output': output,'tool_evaluation': tool_eval,'efficiency_evaluation': efficiency_eval})time.sleep(5)summary = log_evaluation_summary(results)print(f"\nResults:")print(f"Tool Selection: {summary['tool_selection_accuracy']:.1%}")print(f"Efficiency: {summary['efficiency_score']:.1%}")print(f"Overall Score: {summary['overall_score']:.1%}")print("\nView details in Weave dashboard\n")return results, summaryif __name__ == '__main__':run_evaluation()
Run it:
python -m src.evaluation
This takes several minutes due to rate limiting delays between tests. The terminal shows progress as each test completes. When finished, we see summary statistics. More importantly, all results are now stored in Weave for detailed inspection.
What do the evaluation results tell me?
Go back to the Weave dashboard. We should see new traces from the evaluation run.

Evaluation Results Table
After running systematic evaluation, Weave displays aggregate metrics (87% overall quality) alongside detailed per-test breakdowns showing which scenarios passed or failed.
How do I interpret the summary metrics?
The summary shows aggregate performance. Total tests: 16 (we'd have more in a real evaluation). Successful tests: 16 (nothing crashed). Overall score: 0.87 (87% quality).
The 87% tells us the agent performs well but has room for improvement. This isn't a perfect score, which is actually informative. Perfect scores often indicate tests that are too easy or metrics that aren't strict enough. 87% says the agent handles most scenarios correctly but struggles with some edge cases or efficiency issues.
The breakdown shows which metrics contribute to that score. Tool selection accuracy might be high (the agent calls the right functions) while efficiency might be lower (it takes more turns than ideal for some queries).
This quantitative assessment gives us deployment confidence. We're not saying "it seems to work" based on manual testing. We're saying "it achieves 87% quality across 16 diverse test scenarios with documented evidence."
What does the detailed results table show?

Detailed Test Case Results
Each evaluation row shows the exact query, expected tools, and actual latency—this granular view helps identify performance patterns like why error cases take longer than successful queries.
The detailed table shows every test case individually. Each row has: the category grouping similar tests, the expected outcome we defined, the tools we expected the agent to use, the actual customer query, and the model's latency for that query.
Why are some tests slower than others?
Look at the latency column. Most successful cases are completed quickly. But some show 40 to 50 seconds. These slower ones are typically error scenarios, like non-existent orders.
Why the difference? When checking a non-existent order, our agent might retry the lookup, thinking it made a mistake. The retry logic in our rate-limiting code adds delays. The extended time is actually expected behavior for error cases, not a bug.
This latency information guides optimization. If certain query types consistently take longer, we can investigate whether the delay is necessary or if we can optimize those code paths.
How does complete reproducibility help me?
Every test case stores: the exact input query, expected tools and outcomes, actual tools used and outcomes, model latency, and the full execution trace.
This reproducibility is powerful. If a test fails tomorrow that passes today, we can compare the traces side by side to see exactly what changed. Did the model start calling different tools? Did parameter extraction break? Did a function start returning different results? The traces show us precisely.
In practice, we'd use this table to identify problem areas. Sort by latency to find slow queries. Filter by category to focus on a specific feature. Search for keywords to find related failures. The combination of aggregate metrics and detailed traces makes debugging straightforward.
Now that we understand systematic evaluation, we need to think about production deployment.
How do I deploy this to production?
Running locally for tutorials is one thing. Serving real customers is another. Several practical considerations affect production deployment.
What happens to rate limits at scale?
Our development code includes 9-second delays between API calls. This prevents throttling during testing. But it doesn't scale to production.
Imagine handling 100 customer questions per minute. With 9-second delays and 2 API calls per conversation, we could only manage 6 to 7 conversations concurrently. That's completely inadequate for any real business.
The solution: request higher rate limits from AWS. The process is straightforward. Navigate to Service Quotas in AWS Console. Find the Bedrock quotas. Locate the specific quota for Nova Lite requests per minute. Click "Request increase." Specify the desired limit (like 100 requests per minute). Explain the business justification (customer support system handling high query volumes). Submit the request.
AWS typically approves within 24 to 48 hours. There's no additional cost. We still only pay per actual API call made. The higher quota just removes the artificial throttling.
With 100 requests per minute, we could handle 30 to 40 concurrent customer conversations comfortably. For even higher scale, quotas can go into the thousands. This scales to enterprise levels.
What does production performance look like?

Performance Visualization
The p95 latency chart tracks agent performance over time—the 20-second plateau here reflects our rate-limiting delays, not actual model inference time, showing where optimization is needed.
This chart shows latency over time during our evaluation run. The p95 latency (95% of requests complete within this time) reflects typical performance.
It started at 28 seconds (cold start due to AWS allocating resources), spiked to 30 seconds, then gradually decreased to 20 seconds before stabilizing. The 20-second plateau is almost entirely due to our 9-second delay, multiplied by 2 API calls per conversation. The actual model inference time is small. Tool execution time is near zero.
With higher quotas and reduced delays, this latency drops dramatically. We could realistically achieve 2 to 4 seconds per complete customer interaction. That's fast enough for real-time support chat interfaces.
What about the cost of running on Bedrock at scale?
Bedrock charges per token. Tokens are text fragments, roughly equivalent to word pieces. Nova Lite pricing: $0.75 per million input tokens, $3.00 per million output tokens.
A typical interaction uses approximately 450 input tokens (user message, conversation history, and tool definitions) and 180 output tokens (the model's response). The math: (450 / 1,000,000) × $0.75 + (180 / 1,000,000) × $3.00 = approximately $0.001 per interaction. That's one tenth of a cent.
At scale: 10,000 monthly interactions cost about $10. 50,000 interactions cost about $50. 100,000 interactions cost about $100.
This is remarkably inexpensive compared to traditional support costs. A single human support agent costs thousands per month in salary. The AI agent costs dollars per month even at a substantial scale. The cost efficiency is dramatic.
We can improve efficiency further with caching. Many customers ask identical questions. "What's your return policy?" doesn't need a fresh API call every time. Cache that response and serve it instantly for subsequent requests. This reduces both latency and cost.
How do I add new capabilities to my agent?
As the agent proves useful, we'll want to expand its capabilities. The architecture makes this straightforward. To add order cancellation, for example:
Add the tool function to tools.py:@weave.op()def cancel_order(order_id: str, reason: str) -> dict:"""Cancel an order that hasn't shipped"""# ImplementationpassAdd the tool definition to the agent's list:{"toolSpec": {"name": "cancel_order","description": "Cancel order not yet shipped","inputSchema": { /* ... */ }}}Register it in the tool functions map:self.tool_functions["cancel_order"] = cancel_order
The agent now knows how to cancel orders. When customers ask "Can I cancel order ORD-2024-003?", the agent automatically calls the new tool. Weave automatically traces all calls. No other code changes required.
This extensibility is crucial for production. Real customer support involves dozens of operations: updating addresses, applying discount codes, escalating to human agents, checking product availability, processing exchanges. Each becomes a new tool following the same pattern.
How do I connect to real databases and APIs?
Our tutorial uses CSV files for simplicity. Production systems use real databases and APIs. The abstraction pattern we built makes swapping data sources straightforward without changing agent code.
For Shopify integration, we'd create a new data source class that calls Shopify's API instead of reading CSV files. The agent code stays exactly the same. It just calls get_order() and process_return() without knowing or caring where the data comes from.
This separation of concerns is critical for maintainability. We can migrate databases, switch platforms, or change vendors without touching the agent logic. The agent stays focused on customer interaction while the data source layer handles backend integration.
What have we accomplished?
We started with a fundamental problem: AI agents are black boxes. When something goes wrong, we can't see what happened or why. Debugging requires guesswork, trial and error, and hope.
Now we have complete visibility. Every decision the agent makes is traced. Every function call is logged. Every result is captured. The complete execution path from user input to final response is stored and queryable.
What Specific Problems Does This Visibility Solve?
Production debugging becomes straightforward. When a customer reports an issue, we look up their interaction in Weave. We see exactly what happened: which tools were called, what parameters were extracted, what data was returned, and where the process broke down. We deploy a fix based on evidence, not speculation.
Quality improvement becomes data-driven. We run a systematic evaluation against 16 test scenarios. We get quantitative metrics: 87% overall quality with specific breakdowns by category. We identify which scenarios work well and which need improvement. Every code change validates against this test suite.
Performance optimization becomes targeted. We see latency patterns in Weave visualizations. We identify bottlenecks (in our case, rate limiting delays). We measure the impact of optimizations. We track costs per interaction and optimize expensive queries.
How did Weave make this possible?
The @weave.op() decorator provides automatic instrumentation. We add one line per function and get complete observability without writing any logging code. Weave captures inputs and outputs, times operations, builds execution trees, correlates related operations, stores traces persistently, and provides the dashboard for exploration.
Without this automatic approach, we'd spend weeks building observability infrastructure before writing any agent logic. Manual logging, correlation IDs, execution hierarchies, custom dashboards—all that engineering effort just to see what's happening. With Weave, observability comes included from day one.
Building on this foundation Bedrock?
The code from this tutorial is production-ready. It can now serve real customer support requests. The patterns scale to larger systems with more tools, more complex workflows, and higher request volumes.
To take this further
- Add more tools for additional customer support operations (cancellation, address updates, discount application).
- Connect to production systems (Shopify, Salesforce, custom databases).
- Expand evaluation to 50+ test scenarios covering more edge cases.
- Set up monitoring alerts for latency spikes, increased error rates, or cost anomalies.
- Implement A/B testing for different prompt strategies or model configurations.
- Build a feedback loop in which customer interactions inform the growth of the evaluation dataset.
The invisible is now visible. The undebuggable is now debuggable. The unknowable is now knowable. This is what building with observability from day one provides.
Start building: The complete code is available at https://github.com/abduldattijo/bedrock-weave-tutorial
Learn more