You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
Does the agent respond in a different way? Is it running any tools? What happens when you click on the tool execution boxes?
263
+
264
+
## Exercise 3: Add to Cart and Calculate Cart Total
265
+
266
+
In this exercise, you’ll extend the agent with two new tools that make it possible to manage a shopping cart in MongoDB:
267
+
268
+
1.**`add_to_cart`** – adds products to a user’s cart.
269
+
2.**`calculate_cart_total`** – sums the total cost of products in the cart.
270
+
271
+
The cart will be stored in a separate MongoDB collection called **carts**, identified by the username of the shopper. This will require the agent to ask for an username. In a real application, you'd need to implement authorization first.
272
+
273
+
### Step 1: Implement the Tools
274
+
275
+
Open **`mongodb_groceries_agent/agent.py`** and add the following code after the definition of the `find_similar_products` function (around line 75).
276
+
277
+
The code below contains placeholders that you’ll need to replace with the correct variables or methods. Updating these ensures that the tools work correctly with your database and collections.
{"$addToSet": {"products": <PRODUCT_DOCUMENT>}}, # <-- 3. Replace with the product document variable defined above
317
+
upsert=True
318
+
)
319
+
320
+
returnf"Product {product_document['product']} added to your cart."
321
+
322
+
defcalculate_cart_total(username: str) -> str:
323
+
"""Calculates the total price of all products in the user cart.
324
+
This function retrieves the user cart from the carts collection and sums their price to return a total.
325
+
Args:
326
+
username: The name of the user.
327
+
328
+
Returns:
329
+
Total price
330
+
"""
331
+
cart_document = database_client[DATABASE_NAME][CARTS_COLLECTION_NAME].<FIND_METHOD>( # <-- 4. Replace with the correct collection method to find one document
332
+
{"username": username},
333
+
{
334
+
"_id": 0,
335
+
"products": 1
336
+
}
337
+
)
338
+
339
+
total =0
340
+
for product in cart_document["products"]:
341
+
total = total + product["sale_price"]
342
+
343
+
return total
344
+
```
345
+
346
+
Replace the placeholders:
347
+
1. <COLLECTION_NAME> – Replace with the collection variable defined on the previous line.
348
+
2. <PRODUCT_NAME> – Replace with the product argument passed into the function.
349
+
3. <PRODUCT_DOCUMENT> – Replace with the product_document variable defined earlier in the function.
350
+
4. <FIND_METHOD> – Replace with the correct collection method to find a single document.
351
+
352
+
### Step 2: Update the Agent
353
+
354
+
Now, update the agent's instruction to explain its new capabilities and add the new tools to the list of tools.
355
+
356
+
```python
357
+
instruction="""
358
+
You are the **Online Groceries Agent**, a friendly and helpful virtual assistant for our e-commerce grocery store.
359
+
Start every conversation with a warm greeting, introduce yourself as the "Online Groceries Agent," and ask how you can assist the user today.
360
+
Your role is to guide customers through their shopping experience.
361
+
362
+
What you can do:
363
+
- Help users discover and explore products in the store.
364
+
- Suggest alternatives when the exact item is not available.
365
+
- Add products to the user’s shopping cart.
366
+
- Answer product-related questions in a clear and concise way.
367
+
- Return the total in the user’s shopping cart.
368
+
369
+
Available tools:
370
+
1. **find_similar_products**: Search for products with names semantically similar to the user’s request.
371
+
2. **add_to_cart**: Add a product to the user’s cart in MongoDB. Pass only the product name (as it appears in the inventory collection) and the user’s username.
372
+
3. **calculate_cart_total**: Sum the total of all products in a user's cart and return it. Pass the user’s username.
373
+
374
+
Core guidelines:
375
+
- **Always search first**: If a user asks for a product, call `find_similar_products` before attempting to add it to the cart.
376
+
- **Handle missing products**: If the requested product is not in the inventory, suggest similar items returned by the search.
377
+
- **Parallel tool use**: You may call multiple tools in parallel when appropriate (e.g., searching for several items at once).
378
+
- **Clarify only when necessary**: Ask for more details if the request is unclear and you cannot perform a search.
379
+
- Keep your tone positive, approachable, and customer-focused throughout the interaction.
380
+
381
+
Additional important instructions:
382
+
- **Do not assume availability**: Never add a product directly to the cart without confirming it exists in the inventory.
383
+
- **Respect exact names**: When using `add_to_cart`, pass the product name exactly as stored in the inventory collection.
384
+
- **Multi-item requests**: If the user asks for several items in one message, search for all items together and suggest results before adding to the cart.
385
+
- **Quantity requests**: If the user specifies a quantity, repeat it back to confirm and ensure it is respected when adding to the cart.
386
+
- **Cart confirmation**: After adding items, confirm with the user that they have been successfully added.
387
+
- **Fallback behavior**: If no results are found, apologize politely, and encourage the user to try a different product or category.
388
+
- **Stay focused**: Only handle product discovery, shopping, and cart management tasks. Politely decline requests unrelated to groceries.
389
+
- **Answering product questions**: If the question is about a product (e.g., "Is this organic?" or "How much does it cost?"), use the search results to answer. If the information is not available, respond transparently that you don’t have that detail.
390
+
391
+
Remember: you are a professional yet friendly shopping assistant whose goal is to make the user’s grocery shopping smooth, efficient, and enjoyable.
392
+
"""
393
+
394
+
root_agent = Agent(
395
+
model="gemini-2.5-flash",
396
+
name="grocery_shopping_agent",
397
+
instruction=instruction,
398
+
tools=[
399
+
find_similar_products,
400
+
# 5. Add the two new tools to the list
401
+
<ADD_TO_CART_TOOL>,
402
+
<CALCULATE_TOTAL_TOOL>
403
+
]
404
+
)
405
+
```
406
+
407
+
Replace the two placeholders at the bottom:
408
+
-`<ADD_TO_CART_TOOL>`
409
+
-`<CALCULATE_TOTAL_TOOL>`
410
+
411
+
412
+
Stop the running process in the terminal by pressing `Ctrl+C`. Then, run the dev server command again:
413
+
414
+
```
415
+
adk web
416
+
```
417
+
418
+
Test the agent. Here are a few sample prompts:
419
+
420
+
```
421
+
- Add milk, flour, and chocolate to my cart.
422
+
- Show me the best-rated products.
423
+
- I want to bake a chocolate cake—find me the ingredients I’ll need.
424
+
- What’s the total cost of my cart?
425
+
```
426
+
427
+
## Final
428
+
429
+
🎉 Congratulations—you’ve completed the exercises!
430
+
431
+
Complete the short assessment to claim your **AI Agents with MongoDB Skill Badge** here: [mdb.link/adk-london-badge](https://mdb.link/adk-london-badge).
0 commit comments