LangChain Integration Guide

Use BuyWhere's built-in LangChain tools to turn product search, product lookup, and best-price retrieval into agent actions.

This guide walks through:

  • installing the SDK and LangChain dependencies
  • creating BuyWhere tools
  • building a shopping agent
  • handling tool results
  • handling API and runtime errors

Prerequisites

  • Python 3.10+
  • a BuyWhere API key in the format bw_live_xxxxx
  • an OpenAI API key if you want to run the example agent with langchain-openai

1. Install the dependencies

Install the BuyWhere SDK with its LangChain extra, then add your model provider package:

pip install "buywhere-sdk[langchain]" langchain-openai

The buywhere-sdk[langchain] extra installs the LangChain packages required by the BuyWhere tool adapters. The langchain-openai package provides the chat model used in the full shopping-agent example below.

If you are working from this repository instead of PyPI, install the SDK in editable mode:

pip install -e ./sdk[langchain] langchain-openai

2. Set your environment variables

export BUYWHERE_API_KEY="bw_live_xxxxx"
export OPENAI_API_KEY="sk-..."

If you are targeting a non-default BuyWhere environment, also set:

export BUYWHERE_BASE_URL="https://api.buywhere.ai"

3. Create BuyWhere tools

The SDK ships three LangChain tools:

  • BuyWhereSearchTool for product discovery
  • BuyWhereGetProductTool for detailed product lookups by BuyWhere product ID
  • BuyWhereBestPriceTool for cheapest-listing retrieval

You can instantiate them individually or through the bundled toolkit.

Option A: instantiate the toolkit

import os

from buywhere_sdk.langchain import BuyWhereToolkit

toolkit = BuyWhereToolkit(
    api_key=os.environ["BUYWHERE_API_KEY"],
    base_url=os.getenv("BUYWHERE_BASE_URL"),
    timeout=30.0,
)

tools = toolkit.get_tools()

Option B: instantiate tools one by one

import os

from buywhere_sdk.langchain import (
    BuyWhereBestPriceTool,
    BuyWhereGetProductTool,
    BuyWhereSearchTool,
)

search_tool = BuyWhereSearchTool(api_key=os.environ["BUYWHERE_API_KEY"])
get_product_tool = BuyWhereGetProductTool(api_key=os.environ["BUYWHERE_API_KEY"])
best_price_tool = BuyWhereBestPriceTool(api_key=os.environ["BUYWHERE_API_KEY"])

4. Smoke-test the tools directly

Before wiring the tools into an agent, verify that the integration works on its own.

import os

from buywhere_sdk.langchain import BuyWhereToolkit

toolkit = BuyWhereToolkit(api_key=os.environ["BUYWHERE_API_KEY"])
search_tool, get_product_tool, best_price_tool = toolkit.get_tools()

search_result = search_tool.invoke(
    {
        "query": "wireless noise cancelling headphones",
        "max_price": 500,
        "limit": 3,
    }
)
print(search_result)

best_price_result = best_price_tool.invoke({"query": "Nintendo Switch OLED"})
print(best_price_result)

The tools return formatted text that is ready to pass back into an LLM agent loop.

You should see plain-text output similar to:

Found 3 products for 'wireless noise cancelling headphones':

1. Sony WH-1000XM5 Wireless Noise Cancelling Headphones - Black — SGD 479.0 (lazada_sg) [ID: 12345]
   URL: https://...

If this smoke test fails, fix that first before debugging agent behavior. Most integration problems come from missing dependencies, a missing BUYWHERE_API_KEY, or pointing BUYWHERE_BASE_URL at the wrong environment.

5. Build a shopping agent

The example below creates a complete LangChain shopping assistant that can:

  • search the BuyWhere catalog
  • inspect a specific product by ID
  • find the cheapest listing for a known product
  • explain its recommendation in natural language

Create shopping_agent.py:

import os

from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

from buywhere_sdk.langchain import BuyWhereToolkit


def build_agent() -> AgentExecutor:
    toolkit = BuyWhereToolkit(
        api_key=os.environ["BUYWHERE_API_KEY"],
        base_url=os.getenv("BUYWHERE_BASE_URL"),
        timeout=30.0,
    )
    tools = toolkit.get_tools()

    prompt = ChatPromptTemplate.from_messages(
        [
            (
                "system",
                "You are a shopping assistant for Singapore e-commerce. "
                "Use BuyWhere tools to find products, compare prices, and "
                "recommend the best option based on the user's request. "
                "When you recommend a product, include the product name, price, source, "
                "and explain why it fits the request.",
            ),
            ("human", "{input}"),
            ("placeholder", "{agent_scratchpad}"),
        ]
    )

    llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
    agent = create_tool_calling_agent(llm=llm, tools=tools, prompt=prompt)

    return AgentExecutor(
        agent=agent,
        tools=tools,
        verbose=True,
        handle_parsing_errors=True,
    )


if __name__ == "__main__":
    agent_executor = build_agent()

    response = agent_executor.invoke(
        {
            "input": (
                "I need a Nintendo Switch OLED for Singapore. "
                "Find the cheapest in-stock option and summarize the result."
            )
        }
    )

    print(response["output"])

Run it with:

python shopping_agent.py

Expected flow:

  • the model receives the user request
  • LangChain decides which BuyWhere tool to call
  • the tool returns formatted product data
  • the model turns that tool output into a user-facing recommendation

6. Handle results in your application

The BuyWhere LangChain tools return human-readable strings. That makes them easy to use in chat agents, but you may still want application-side post-processing.

Common patterns:

  • show the raw tool output in an agent trace for debugging
  • capture the agent's final answer separately from intermediate tool calls
  • ask the model to restate product recommendations in a fixed response template for your UI

Example:

response = agent_executor.invoke(
    {"input": "Find a Dyson vacuum under SGD 900 and tell me the best option."}
)

final_answer = response["output"]
print(final_answer)

If you need structured product data for your own application logic, use the base SDK client directly alongside LangChain:

import os

from buywhere_sdk import BuyWhere

client = BuyWhere(api_key=os.environ["BUYWHERE_API_KEY"])
results = client.search("Dyson vacuum", max_price=900, limit=5)

for product in results.items:
    print(product.id, product.name, product.price, product.source)

Use that pattern when your application needs typed fields such as product.id, product.price, or product.buy_url, and reserve the LangChain tools for LLM-facing tool execution.

7. Understand when to use each tool

Use the tools deliberately so the agent stays predictable:

  • BuyWhereSearchTool: open-ended product discovery such as "find gaming monitors under SGD 500"
  • BuyWhereGetProductTool: fetch richer details after the agent already knows a BuyWhere product ID
  • BuyWhereBestPriceTool: shortcut for "find the cheapest listing for this exact product"

A common pattern is:

  1. search for candidate products
  2. inspect one or two promising product IDs in detail
  3. call best-price when the user has already narrowed to a specific product family

8. Add error handling

For production use, handle both BuyWhere API errors and LangChain runtime errors.

import os

from langchain.agents import AgentExecutor, create_tool_calling_agent
from langchain_core.prompts import ChatPromptTemplate
from langchain_openai import ChatOpenAI

from buywhere_sdk.exceptions import (
    AuthenticationError,
    BuyWhereError,
    NotFoundError,
    RateLimitError,
    ServerError,
    ValidationError,
)
from buywhere_sdk.langchain import BuyWhereToolkit


def build_agent() -> AgentExecutor:
    toolkit = BuyWhereToolkit(api_key=os.environ["BUYWHERE_API_KEY"])
    tools = toolkit.get_tools()

    prompt = ChatPromptTemplate.from_messages(
        [
            ("system", "You are a shopping assistant that uses BuyWhere tools."),
            ("human", "{input}"),
            ("placeholder", "{agent_scratchpad}"),
        ]
    )

    llm = ChatOpenAI(model="gpt-4o-mini", temperature=0)
    agent = create_tool_calling_agent(llm=llm, tools=tools, prompt=prompt)

    return AgentExecutor(
        agent=agent,
        tools=tools,
        verbose=False,
        handle_parsing_errors=True,
    )


agent_executor = build_agent()

try:
    response = agent_executor.invoke(
        {"input": "Find the best price for Apple AirPods Pro in Singapore."}
    )
    print(response["output"])
except AuthenticationError:
    print("Your BuyWhere API key is missing, invalid, or expired.")
except RateLimitError:
    print("BuyWhere rate limit exceeded. Retry with backoff.")
except ValidationError as exc:
    print(f"Request validation failed: {exc}")
except NotFoundError:
    print("No matching products were found.")
except ServerError:
    print("BuyWhere returned a server error. Retry later.")
except BuyWhereError as exc:
    print(f"BuyWhere request failed: {exc}")
except Exception as exc:
    print(f"Unexpected LangChain or model error: {exc}")

9. Troubleshooting

ModuleNotFoundError: No module named 'langchain_openai'

Install the model provider package:

pip install langchain-openai

If you are developing from this repository, also make sure you installed the SDK extras:

pip install -e ./sdk[langchain]

Authentication failed

Confirm that:

  • BUYWHERE_API_KEY is set
  • the key is valid for the environment you are targeting
  • BUYWHERE_BASE_URL points at the right BuyWhere deployment

The agent gives generic answers without using the tools

Check that:

  • you passed tools=toolkit.get_tools() into the agent
  • your prompt explicitly tells the agent to use BuyWhere tools
  • your model supports tool calling

You need structured output instead of text

Use the base BuyWhere SDK client for typed data retrieval and keep the LangChain tools for the model-facing reasoning loop.

Next steps