GitHub
Cookbook

Dynamic Context Assembly

Construct precise context blocks for e-commerce agents using structured graph retrieval.

Domain: E-Commerce
Key Concepts: Ontology, Filtering, Graph Traversal (BFS)

Problem Statement

Generic RAG dumps unstructured chunks of text into the context window. But complex agents need structure. For a shopping assistant, an agent needs to differentiate between a Product (entity) and a Purchase (event), and traverse relationships (e.g., "Find other products by this Brand").

Architecture: Structured Retrieval

Instead of a single "get relevant stuff" call, we assemble the context from three distinct retrieval strategies:

Implementation Steps

1. Ontology-Driven Ingestion

We define a schema so the memory system understands our specific domain entities.

# Define the schema
client.kg.define_schema(
kg_name="ecommerce_kg",
schema={
"entities": ["Product", "Brand", "Category", "User"],
"relations": ["PURCHASED", "VIEWED", "MANUFACTURED_BY", "BELONGS_TO"]
}
)
# Ingest a Product
client.kg.add_entity(
kg_name="ecommerce_kg",
entity_id="prod_123",
label="Product",
properties={
"name": "TrailMaster 5000",
"price": 120.00,
"features": ["waterproof", "trail_running"]
}
)

2. Retrieval Strategy: Graph Traversal (BFS)

The user asked about "socks for these" (referring to shoes in cart). We use graph traversal to find the brand of the shoes, then find socks by that brand.

# 1. Get the current session "anchor" (the item in cart)
cart_item_id = "prod_123" # TrailMaster 5000
# 2. Traverse: Product -> Brand -> Related Products
related_products = client.graph.traverse(
start_nodes=[cart_item_id],
bg_name="ecommerce_kg",
relationships=["MANUFACTURED_BY", "MANUFACTURES"], # Go up to Brand, then down to Products
depth=2,
filters={"label": "Product", "category": "Socks"} # Only find Socks
)
print(related_products)
# Output: ["ProRunner Socks (Same Brand)", "Trail Socks (Same Brand)"]

3. Context Assembly

Finally, we format the retrieved data into XML-tagged blocks for the LLM. This makes the data strictly readable and reduces hallucination.

def assemble_prompt(cart_context, related_products):
return f"""
<CURRENT_CART>
{format_product(cart_context)}
</CURRENT_CART>
<RELATED_PRODUCTS_BY_BRAND>
{format_list(related_products)}
</RELATED_PRODUCTS_BY_BRAND>
User Query: "Do you have socks for these?"
"""
# Resulting Prompt:
# <CURRENT_CART>
# Product: TrailMaster 5000
# Brand: SpeedDemons
# </CURRENT_CART>
# <RELATED_PRODUCTS_BY_BRAND>
# - ProRunner Socks ($12)
# - Trail Socks ($15)
# </RELATED_PRODUCTS_BY_BRAND>

Why This Matters

By using Graph Traversal instead of just vector search, we found socks that are logically related (same brand) to the cart item, even if the user didn't mention the brand name. The Structured Context ensures the LLM knows exactly which item is in the cart versus which items are recommendations.