Skip to content
askdareDocumentation

    A product page assistant

    A chat beside each product that knows which product the page shows. The visitor asks "Is it good for two people?" without naming it, and the bot answers about this tent; asked for something lighter or cheaper, it shows other products as cards that link to their pages. The same works for a SaaS pricing page, with plans instead of products.

    Page:    Ridge 2 tent, €349.00
    Visitor: Is it good for two people?
    Bot:     Yes: it sleeps two and weighs 1.4 kg. For campsites, the Meadow 3 has more room.
    
             ┌ Ridge 2 tent ─┐ ┌ Meadow 3 tent ┐ ┌ Summit 2 tent ──────────┐
             │ €349.00       │ │ €279.00       │ │ €599.00 · out of stock  │
             │ [ Compare ]   │ │ [ Compare ]   │ │ [ Compare ]             │
             └───────────────┘ └───────────────┘ └─────────────────────────┘
    FeatureGuide
    Page context: the product the page shows, sent with the visitor's messageStyling: page JavaScript, React: Root
    Tools that read your catalogTools
    Product cards in the chat inside your pageReact: tool cards

    The code is in site/recipes/product-page/, with five made-up products in catalog.ts.

    1. The bot accepts page context

    pageContext: true lets the page describe itself to the bot. From bot.ts:

    export const productBot = defineBot({
      id: 'products',
      model: process.env.ASKDARE_MODEL ?? '',
      instructions: ({ locale }) =>
        [
          'You are the assistant on the product pages of an outdoor shop. You answer questions about its products.',
          "The visitor's message may come with a description of the page they are on. Use it to know which product they mean, and look the product up with get_product before you state a price or a specification.",
          'For alternatives or products that go with it, use find_products: the visitor sees them as cards, so name them briefly.',
          `Reply in the visitor's language; default to ${locale}.`,
        ].join(' '),
      tools: [getProduct, findProducts],
      pageContext: true,
    });

    Page context is what the visitor's browser says. Anyone can change it, so askdare sends it as a marked part of the visitor's own message, never as instructions, and it gets no more trust than what they type. That's why the bot looks the price up with a tool instead of repeating the page: a tampered context can at worst make the bot look up another product, which anyone may see.

    2. The page passes the product

    The page is a Server Component that reads the product, and the chat a client component that passes a short description as context (up to 1,000 characters). From page.tsx and product-chat.tsx:

    export default async function ProductPage({ params }: { params: Promise<{ sku: string }> }) {
      const product = await catalog.get(decodeURIComponent((await params).sku));
      if (!product) notFound();
      const price = formatPrice(product.price);
      return (
        <main>
          <h1>{product.name}</h1>
          <aside aria-label="Ask about this product">
            <ProductChat
              config={getChatConfig({ bots, bot: 'products' })}
              product={{ sku: product.sku, name: product.name, price }}
            />
          </aside>
        </main>
      );
    }
    <Chat.Root
      config={config}
      context={`Product page: ${product.name} (SKU ${product.sku}), ${product.price}.`}
      greeting={`Questions about the ${product.name}?`}
      starters={['Is it good for two people?', 'What goes with it?']}
      toolRenderers={toolRenderers}
    >
      <Chat.DefaultChat className="product-chat" />
    </Chat.Root>

    The context is sent again only when it changes, so a visitor who moves to another product's page (and another Root context) talks about that one. With the script-tag widget, the same goes in askdare('configure', { context }) on each product page.

    3. Tools and cards

    get_product looks one product up by SKU; find_products lists a category up to a price. Both return the fields a visitor may see, never the supplier's cost, and build each product's link from the catalog, never from what the model wrote. From tools.ts:

    export const findProducts = defineTool({
      name: 'find_products',
      description:
        'Products of a category, optionally up to a price. Use it to suggest alternatives or products that go with the one on the page.',
      input: z.object({
        category: z.enum(['tent', 'sleeping-bag', 'stove']),
        maxPriceEuros: z.number().int().positive().nullable().describe('Highest price in euros, or null'),
      }),
      execute: async ({ category, maxPriceEuros }) => {
        const products = await catalog.search({
          category,
          maxPrice: maxPriceEuros === null ? null : maxPriceEuros * 100,
        });
        return { products: products.slice(0, 4).map(publicFields) };
      },
      ui: ({ products }) => ({
        products: products.map(({ sku, name, price, inStock, path }) => ({ sku, name, price, inStock, path })),
      }),
    });

    The cards in product-cards.tsx link to each product's page and offer "Compare", which sends a message as the visitor:

    function ProductCards({ data }: Chat.ToolRendererProps<typeof findProducts>): ReactElement {
      const { actions, state } = Chat.useChat();
      return (
        <ul className="product-cards">
          {data.products.map((product) => (
            <li key={product.sku}>
              <Link href={product.path}>{product.name}</Link>
              <p>{product.price}{product.inStock ? '' : ' · out of stock'}</p>
              <button type="button" disabled={state.busy} onClick={() => void actions.send(`How does the ${product.name} compare?`)}>
                Compare
              </button>
            </li>
          ))}
        </ul>
      );
    }

    Images work the same way: load them only from URLs your tool builds from the catalog, never from the model's arguments (React: tool cards).

    Make it yours

    ReplaceWithGuide
    catalog in catalog.tsYour product API, search or database. Keep the fields the model sees few: they cost tokens on every later messageTools: rules
    The categories in find_productsYour own, as an enum: what a field accepts is what the model can ask forTools
    The context textWhat the visitor sees on the page that the bot should know: the product, the plan, the variant pickedStyling: page JavaScript
    productPathYour product URLs. Absolute links to other sites go in Chat.LinkReact: tool cards
    The chat's placeDefaultChat in an aside, or the script-tag widget with your own page in its iframe for the cardsEmbedding