人工智能购物助手接受自然语言查询,例如“为我找到 100 美元以下且好评如潮的无线耳机”,并返回由亚马逊实时数据支持的排名产品推荐。这种类型的助手将用于意图解析和推荐生成的法学硕士与用于新鲜库存和定价的实时产品搜索 API 相结合。本教程使用 LangChain、为 Amazon 配置的 ScavioSearch 和简单的对话循环构建这样的助手。
前置条件
- Python 3.10 或更高版本
- pip install langchain langchain-scavio langchain-openai
- Scavio API 密钥
- OpenAI API 密钥
操作指南
步骤 1: 配置亚马逊搜索工具
使用亚马逊平台实例化 ScadioSearch。这使得 LangChain 代理可以访问实时亚马逊产品搜索。
from langchain_scavio import ScavioSearch
amazon_tool = ScavioSearch(
api_key="your_scavio_api_key",
platform="amazon",
marketplace="US",
max_results=10
)步骤 2: 构建系统提示符
定义一个系统提示,指示法学硕士充当购物助理并清晰地格式化推荐。
SYSTEM_PROMPT = (
"You are a helpful shopping assistant. When the user asks for product recommendations, "
"use the search tool to find current Amazon listings. Always mention price, rating, and "
"a brief reason for each recommendation. Keep responses concise."
)步骤 3: 创建代理
根据导购系统提示,将亚马逊工具接入LangChain代理。
from langchain_openai import ChatOpenAI
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate
llm = ChatOpenAI(model="gpt-4o", temperature=0)
prompt = ChatPromptTemplate.from_messages([
("system", SYSTEM_PROMPT),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
])
agent = create_tool_calling_agent(llm, [amazon_tool], prompt)
executor = AgentExecutor(agent=agent, tools=[amazon_tool])步骤 4: 运行购物查询
使用自然语言购物请求调用助手并打印响应。
response = executor.invoke({
"input": "Find me the best wireless headphones under $150 with noise cancellation"
})
print(response["output"])Python 示例
import os
from langchain_scavio import ScavioSearch
from langchain_openai import ChatOpenAI
from langchain.agents import create_tool_calling_agent, AgentExecutor
from langchain_core.prompts import ChatPromptTemplate
os.environ["OPENAI_API_KEY"] = "your_openai_key"
tool = ScavioSearch(api_key=os.environ["SCAVIO_API_KEY"], platform="amazon", marketplace="US")
llm = ChatOpenAI(model="gpt-4o", temperature=0)
prompt = ChatPromptTemplate.from_messages([
("system", "You are a helpful shopping assistant. Use the search tool to find products."),
("human", "{input}"),
("placeholder", "{agent_scratchpad}"),
])
agent = create_tool_calling_agent(llm, [tool], prompt)
executor = AgentExecutor(agent=agent, tools=[tool], verbose=True)
if __name__ == "__main__":
result = executor.invoke({"input": "Best noise-canceling headphones under $150"})
print(result["output"])JavaScript 示例
const { ChatOpenAI } = require("@langchain/openai");
const { DynamicTool } = require("@langchain/core/tools");
const { AgentExecutor, createToolCallingAgent } = require("langchain/agents");
const { ChatPromptTemplate } = require("@langchain/core/prompts");
const API_KEY = process.env.SCAVIO_API_KEY;
const amazonTool = new DynamicTool({
name: "amazon_search",
description: "Search Amazon for products. Input is a product search query.",
func: async (query) => {
const res = await fetch("https://api.scavio.dev/api/v1/search", {
method: "POST",
headers: { "x-api-key": API_KEY, "Content-Type": "application/json" },
body: JSON.stringify({ platform: "amazon", query, marketplace: "US" })
});
const data = await res.json();
return JSON.stringify((data.products || []).slice(0, 5));
}
});
async function main() {
const llm = new ChatOpenAI({ model: "gpt-4o" });
const prompt = ChatPromptTemplate.fromMessages([
["system", "You are a helpful shopping assistant."],
["human", "{input}"],
["placeholder", "{agent_scratchpad}"]
]);
const agent = await createToolCallingAgent({ llm, tools: [amazonTool], prompt });
const executor = new AgentExecutor({ agent, tools: [amazonTool] });
const result = await executor.invoke({ input: "Best wireless headphones under $150" });
console.log(result.output);
}
main().catch(console.error);预期输出
Based on current Amazon listings, here are the top noise-canceling headphones under $150:
1. Anker Soundcore Q45 — $59.99 (4.4 stars, 28,000+ reviews)
Great ANC for the price, up to 50 hours battery life.
2. Sony WH-CH720N — $149.00 (4.5 stars, 15,000+ reviews)
Lightweight with Sony's proprietary ANC, folds flat.