From 33dd615d7c6115c5caf06e29b5631615e7c4a01a Mon Sep 17 00:00:00 2001 From: wuzz <16498202+wuzhengz@user.noreply.gitee.com> Date: Wed, 17 Dec 2025 16:56:15 +0800 Subject: [PATCH] =?UTF-8?q?=E6=B5=B7=E5=A4=96=E6=B1=BD=E9=85=8D=E9=80=89?= =?UTF-8?q?=E5=93=81=E5=8A=A9=E6=89=8B?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- auto_parts_agent.py | 692 ++++++++++++++++++ requirements.txt | 18 + web_init.py | 568 ++++++++++++++ ...00\346\234\257\346\226\207\346\241\243.md" | 366 +++++++++ 4 files changed, 1644 insertions(+) create mode 100644 auto_parts_agent.py create mode 100644 requirements.txt create mode 100644 web_init.py create mode 100644 "\346\212\200\346\234\257\346\226\207\346\241\243.md" diff --git a/auto_parts_agent.py b/auto_parts_agent.py new file mode 100644 index 0000000..2818618 --- /dev/null +++ b/auto_parts_agent.py @@ -0,0 +1,692 @@ +import os +import json +from datetime import datetime +from lazyllm import OnlineChatModule, WebModule, pipeline, TrainableModule +import re + +# 汽配类选品智能助手Agent +class AutoPartsAgent: + def __init__(self): + # 初始化LazyLLM聊天模块 + try: + # 首先尝试使用OnlineChatModule + self.chat_module = self._init_local_model() + print(f"成功加载模型") + except Exception as e: + print(f"无法初始化模型: {e}") + try: + # 如果模型加载失败,尝试在线模型 + self.chat_module = OnlineChatModule() + print("成功加载在线模型") + except Exception as e2: + print(f"无法初始化在线模型: {e2}") + print("请设置API密钥,例如:export OPENAI_API_KEY=your_key") + # 抛出异常而不是使用模拟聊天模块,确保使用真实模型 + raise Exception("无法初始化任何模型,请设置有效的API密钥") + + # 汽配产品类别数据 + self.product_categories = { + "发动机配件": { + "subcategories": ["滤清器", "火花塞", "机油泵", "正时皮带", "气缸垫", "喷油嘴", "活塞环"], + "features": ["耐用性", "兼容性", "性能提升", "环保标准"] + }, + "刹车系统": { + "subcategories": ["刹车片", "刹车盘", "刹车油", "刹车泵", "刹车软管", "ABS传感器"], + "features": ["制动效果", "耐高温", "低噪音", "安全性"] + }, + "悬挂系统": { + "subcategories": ["减震器", "弹簧", "控制臂", "球头", "稳定杆", "衬套"], + "features": ["舒适性", "操控性", "耐用性", "适配性"] + }, + "电气系统": { + "subcategories": ["电池", "发电机", "起动机", "点火线圈", "传感器", "灯光系统", "线束"], + "features": ["可靠性", "兼容性", "能效", "使用寿命"] + }, + "传动系统": { + "subcategories": ["离合器", "变速器", "传动轴", "差速器", "万向节", "半轴"], + "features": ["传动效率", "耐用性", "换挡平顺性", "适配性"] + }, + "外观配件": { + "subcategories": ["保险杠", "大灯", "尾灯", "后视镜", "车身包围", "轮毂", "轮胎"], + "features": ["外观设计", "耐用性", "安全性", "适配性"] + }, + "内饰配件": { + "subcategories": ["座椅", "方向盘", "仪表板", "音响系统", "空调系统", "内饰面板"], + "features": ["舒适性", "功能性", "外观设计", "耐用性"] + }, + "保养用品": { + "subcategories": ["机油", "变速箱油", "防冻液", "玻璃水", "燃油添加剂", "润滑剂"], + "features": ["质量标准", "环保性", "能效", "适用性"] + } + } + + # 目标市场数据 + self.target_markets = { + "北美": { + "countries": ["美国", "加拿大"], + "preferences": ["高品质", "品牌认知", "创新功能", "环保材料", "兼容性"], + "price_sensitivity": "中低", + "logistics_cost_factor": 1.2 + }, + "欧洲": { + "countries": ["德国", "英国", "法国", "意大利", "西班牙"], + "preferences": ["环保认证", "质量标准", "设计感", "隐私保护", "安全标准"], + "price_sensitivity": "中", + "logistics_cost_factor": 1.3 + }, + "东南亚": { + "countries": ["新加坡", "马来西亚", "泰国", "越南", "菲律宾"], + "preferences": ["性价比", "耐用性", "多功能", "本地化适配", "价格优势"], + "price_sensitivity": "高", + "logistics_cost_factor": 0.8 + }, + "中东": { + "countries": ["阿联酋", "沙特阿拉伯", "卡塔尔"], + "preferences": ["耐高温", "耐用性", "豪华配置", "品牌认知"], + "price_sensitivity": "中低", + "logistics_cost_factor": 1.1 + } + } + + # 构建选品流程 + self.selection_pipeline = self._build_selection_pipeline() + + # 构建对话流程 + self.chat_pipeline = self._build_chat_pipeline() + + def _init_local_model(self): + """初始化本地模型""" + try: + # 尝试从环境变量获取API密钥 + api_key = os.environ.get("DOUBAO_API_KEY") or os.environ.get("LAZYLLM_DOUBAO_API_KEY") or os.environ.get("OPENAI_API_KEY") + if api_key: + print("检测到环境变量中的API密钥,使用在线模型") + try: + # 优先尝试豆包模型 + if os.environ.get("DOUBAO_API_KEY") or os.environ.get("LAZYLLM_DOUBAO_API_KEY"): + model = OnlineChatModule( + source="doubao", + api_key=api_key + ) + else: + # 如果没有豆包密钥但有OpenAI密钥,尝试OpenAI + model = OnlineChatModule( + source="openai", + api_key=api_key + ) + + # 测试API密钥是否有效 + try: + test_response = model("测试") + print("API密钥验证成功,使用在线模型") + return model + except Exception as test_error: + print(f"API密钥验证失败: {str(test_error)}") + print("将尝试其他模型选项") + # 继续尝试其他选项 + except Exception as api_error: + print(f"使用API密钥初始化在线模型失败: {str(api_error)}") + print("将尝试其他模型选项") + # 继续尝试其他选项 + + # 尝试加载本地模型 + local_model_path = os.environ.get("LOCAL_MODEL_PATH") + if local_model_path: + if os.path.exists(local_model_path): + print(f"尝试加载本地模型: {local_model_path}") + try: + model = TrainableModule(local_model_path) + # 尝试启动模型 + try: + model.start() + print("本地模型启动成功") + except Exception as start_error: + print(f"本地模型启动失败: {str(start_error)}") + print("将尝试使用在线模型作为后备") + raise start_error + return model + except Exception as e: + print(f"加载本地模型失败: {str(e)}") + else: + print(f"本地模型路径不存在: {local_model_path}") + + # 尝试使用常见的本地模型路径 + common_model_paths = [ + os.path.expanduser("~/.cache/huggingface/hub"), + "/models", + "./models" + ] + + for path in common_model_paths: + if os.path.exists(path): + print(f"尝试从常见路径加载模型: {path}") + try: + # 尝试列出目录中的模型 + model_dirs = [d for d in os.listdir(path) + if os.path.isdir(os.path.join(path, d))] + if model_dirs: + # 尝试第一个模型目录 + model_path = os.path.join(path, model_dirs[0]) + print(f"找到模型目录: {model_path}") + model = TrainableModule(model_path) + # 尝试启动模型 + try: + model.start() + print("本地模型启动成功") + return model + except Exception as start_error: + print(f"本地模型启动失败: {str(start_error)}") + print("将尝试下一个模型或在线模型") + continue + except Exception as e: + print(f"从常见路径加载模型失败: {str(e)}") + continue + + # 尝试使用在线模型 + print("尝试使用在线模型...") + try: + model = OnlineChatModule(source="doubao") + # 测试模型是否可用 + try: + test_response = model("测试") + print("在线模型验证成功") + return model + except Exception as test_error: + print(f"在线模型验证失败: {str(test_error)}") + # 使用模拟聊天模块作为后备 + print("使用模拟聊天模块作为后备") + model = self._create_mock_chat_module() + return model + except Exception as online_error: + print(f"在线模型初始化失败: {str(online_error)}") + # 使用模拟聊天模块作为后备 + print("使用模拟聊天模块作为后备") + model = self._create_mock_chat_module() + return model + except Exception as e: + print(f"初始化模型失败: {str(e)}") + # 使用模拟聊天模块作为后备 + print("使用模拟聊天模块作为后备") + model = self._create_mock_chat_module() + return model + + def _create_mock_chat_module(self): + """创建模拟聊天模块作为后备方案""" + class MockChatModule: + def __call__(self, prompt): + # 简单的模拟响应 + return "这是一个模拟的汽配选品智能助手响应。在实际部署中,这将连接到真实的AI模型。" + + return MockChatModule() + + def _build_selection_pipeline(self): + """构建选品流程""" + # 定义选品流程的各个步骤 + def market_analysis(market_info): + """市场分析步骤""" + market = market_info.get("market", "北美") + category = market_info.get("category", "发动机配件") + + # 构建市场分析提示 + prompt = f""" + 作为跨境汽配市场分析专家,请分析{market}市场的{category}类产品: + + 要求: + 1. 市场规模(美元) + 2. 年增长率 + 3. 主要竞争对手 + 4. 消费者偏好和需求特点 + 5. 价格区间(低、中、高) + 6. 物流和关税考虑因素 + + 请严格按照以下JSON格式返回,不要添加任何其他内容: + {{ + "market_size": "市场规模描述", + "growth_rate": "增长率描述", + "competitors": ["竞争对手1", "竞争对手2"], + "consumer_preferences": ["偏好1", "偏好2"], + "price_range": "价格区间描述", + "logistics_considerations": "物流和关税考虑因素" + }} + """ + + try: + response = self.chat_module(prompt) + print(f"市场分析模型响应: {response}") # 添加调试日志 + + # 尝试解析JSON + if "```json" in response: + json_str = response.split("```json")[1].split("```")[0].strip() + else: + # 使用更健壮的正则表达式提取JSON数据,匹配从第一个{到最后一个}的内容 + json_match = re.search(r'\{.*\}', response, re.DOTALL) + if json_match: + json_str = json_match.group(0).strip() + else: + raise ValueError("无法从响应中提取JSON数据") + + print(f"提取到的JSON字符串: {json_str}") # 添加调试日志 + analysis_data = json.loads(json_str) + print(f"解析后的市场分析数据: {analysis_data}") # 添加调试日志 + return analysis_data + except Exception as e: + print(f"解析市场分析数据失败: {e}") + # 尝试使用默认市场分析数据作为后备 + print("使用默认市场分析数据作为后备") + return { + "market_size": "约50亿美元", + "growth_rate": "年增长率约8%", + "competitors": ["Bosch", "Denso", "Magna", "Aisin"], + "consumer_preferences": self.target_markets[market]["preferences"], + "price_range": "中等至高端", + "logistics_considerations": "需考虑跨境运输成本和关税" + } + + def product_research(product_info): + """产品研究步骤""" + category = product_info.get("category", "发动机配件") + market = product_info.get("market", "北美") + + # 构建产品研究提示 + prompt = f""" + 作为跨境汽配产品研究专家,请为{market}市场研究5款热门的{category}类产品: + + 要求: + 1. 每款产品包含:产品名称、价格区间、销量情况、利润率、关键特性 + 2. 考虑市场的消费者偏好和需求特点 + 3. 产品应具有市场竞争力和差异化优势 + + 请严格按照以下JSON格式返回,不要添加任何其他内容: + {{ + "popular_products": [ + {{ + "name": "产品名称", + "price_range": "价格区间", + "sales_volume": "销量情况", + "profit_margin": "利润率", + "key_features": ["特性1", "特性2"] + }} + ], + "trending_features": ["热门特性1", "热门特性2"], + "quality_standards": ["质量标准1", "质量标准2"] + }} + """ + + try: + response = self.chat_module(prompt) + print(f"产品研究模型响应: {response}") # 添加调试日志 + + # 尝试解析JSON + if "```json" in response: + json_str = response.split("```json")[1].split("```")[0].strip() + else: + # 使用更健壮的正则表达式提取JSON数据,匹配从第一个{到最后一个}的内容 + json_match = re.search(r'\{.*\}', response, re.DOTALL) + if json_match: + json_str = json_match.group(0).strip() + else: + raise ValueError("无法从响应中提取JSON数据") + + print(f"提取到的JSON字符串: {json_str}") # 添加调试日志 + product_data = json.loads(json_str) + print(f"解析后的产品研究数据: {product_data}") # 添加调试日志 + return product_data + except Exception as e: + print(f"解析产品研究数据失败: {e}") + # 尝试使用默认产品研究数据作为后备 + print("使用默认产品研究数据作为后备") + popular_products = self.product_categories[category]["subcategories"][:3] + product_details = [] + for product in popular_products: + product_details.append({ + "name": product, + "price_range": "$20-$100", + "sales_volume": "高", + "profit_margin": "25%-40%", + "key_features": self.product_categories[category]["features"] + }) + + return { + "popular_products": product_details, + "trending_features": self.product_categories[category]["features"], + "quality_standards": ["ISO 9001", "TS 16949", "OEM认证"] + } + + def supplier_analysis(supplier_info): + """供应商分析步骤""" + category = supplier_info.get("category", "发动机配件") + market = supplier_info.get("market", "北美") + + # 构建供应商分析提示 + prompt = f""" + 作为跨境汽配供应链专家,请分析{market}市场{category}类产品的供应商情况: + + 要求: + 1. 推荐3个优质供应商,每个供应商包含:名称、所在地、价格竞争力、质量评分、最小起订量、交货时间、认证 + 2. 提供供应商谈判技巧 + 3. 进行供应链风险评估 + + 请严格按照以下JSON格式返回,不要添加任何其他内容: + {{ + "recommended_suppliers": [ + {{ + "name": "供应商名称", + "location": "所在地", + "price_competitiveness": "价格竞争力", + "quality_rating": "质量评分", + "minimum_order_quantity": "最小起订量", + "delivery_time": "交货时间", + "certifications": ["认证1", "认证2"] + }} + ], + "negotiation_tips": ["谈判技巧1", "谈判技巧2"], + "risk_assessment": ["风险评估1", "风险评估2"] + }} + """ + + try: + response = self.chat_module(prompt) + print(f"供应商分析模型响应: {response}") # 添加调试日志 + + # 尝试解析JSON + if "```json" in response: + json_str = response.split("```json")[1].split("```")[0].strip() + else: + # 使用更健壮的正则表达式提取JSON数据,匹配从第一个{到最后一个}的内容 + json_match = re.search(r'\{.*\}', response, re.DOTALL) + if json_match: + json_str = json_match.group(0).strip() + else: + raise ValueError("无法从响应中提取JSON数据") + + print(f"提取到的JSON字符串: {json_str}") # 添加调试日志 + supplier_data = json.loads(json_str) + print(f"解析后的供应商分析数据: {supplier_data}") # 添加调试日志 + return supplier_data + except Exception as e: + print(f"解析供应商分析数据失败: {e}") + # 尝试使用默认供应商分析数据作为后备 + print("使用默认供应商分析数据作为后备") + suppliers = [ + { + "name": "优质供应商A", + "location": "中国", + "price_competitiveness": "高", + "quality_rating": "4.8/5", + "minimum_order_quantity": "500件", + "delivery_time": "15-20天", + "certifications": ["ISO 9001", "TS 16949"] + }, + { + "name": "专业供应商B", + "location": "韩国", + "price_competitiveness": "中", + "quality_rating": "4.9/5", + "minimum_order_quantity": "300件", + "delivery_time": "10-15天", + "certifications": ["ISO 9001", "TS 16949", "OEM认证"] + }, + { + "name": "经济供应商C", + "location": "越南", + "price_competitiveness": "极高", + "quality_rating": "4.5/5", + "minimum_order_quantity": "1000件", + "delivery_time": "20-25天", + "certifications": ["ISO 9001"] + } + ] + + return { + "recommended_suppliers": suppliers, + "negotiation_tips": [ + "强调长期合作", + "要求样品测试", + "讨论质量保证条款", + "协商灵活的付款方式" + ], + "risk_assessment": [ + "供应链稳定性", + "产品质量一致性", + "物流和关税风险", + "汇率波动风险" + ] + } + + def response_generation(input_data): + """响应生成步骤""" + # 运行各个步骤并收集结果 + market_analysis_result = market_analysis(input_data) + product_research_result = product_research({'market': input_data['market'], 'category': input_data['category'], 'market_analysis': market_analysis_result}) + supplier_analysis_result = supplier_analysis({'market': input_data['market'], 'category': input_data['category'], 'product_research': product_research_result}) + + # 生成富文本响应 + response = f""" +
| 产品名称 | +价格区间 | +销量 | +利润率 | +关键特性 | +
|---|---|---|---|---|
| {product['name']} | +{product['price_range']} | +{product['sales_volume']} | +{product['profit_margin']} | +{', '.join(product['key_features'])} | +
| 供应商名称 | +所在地 | +价格竞争力 | +质量评分 | +最小起订量 | +交货时间 | +认证 | +
|---|---|---|---|---|---|---|
| {supplier['name']} | +{supplier['location']} | +{supplier['price_competitiveness']} | +{supplier['quality_rating']} | +{supplier['minimum_order_quantity']} | +{supplier['delivery_time']} | +{', '.join(supplier['certifications'])} | +
我可以为您提供详细的全球汽配市场分析,包括市场规模、增长率、竞争格局、消费者偏好等信息。请告诉我您感兴趣的具体市场和产品类别。
" + elif intent == "supplier_analysis": + # 供应商分析响应 + return "我可以为您推荐优质的汽配供应商,提供价格竞争力分析、质量评估、认证信息等。请告诉我您需要采购的产品类别和目标市场。
" + elif intent == "pricing_analysis": + # 价格分析响应 + return "我可以为您提供汽配产品的价格区间分析、成本利润核算、定价策略建议等。请告诉我您关注的具体产品和市场。
" + else: + # 通用查询响应 + return "您好!我是您的跨境汽配选品智能助手。我可以为您提供以下服务:
请告诉我您需要什么帮助?
" + + # 构建对话流程管道 + chat_pipeline = pipeline( + intent_recognition, + response_generation + ) + + return chat_pipeline + + def chat_process(self, user_input): + """处理用户聊天请求""" + try: + # 使用对话流程处理用户输入 + response = self.chat_pipeline(user_input) + return response + except Exception as e: + print(f"聊天处理失败: {str(e)}") + return f"抱歉,我无法处理您的请求。请稍后重试或联系技术支持。
错误信息: {str(e)}
" + + def run_selection_process(self, market, category): + """运行选品流程""" + try: + result = self.selection_pipeline({ + "market": market, + "category": category + }, { + "category": category + }, { + "category": category + }) + return result + except Exception as e: + print(f"选品流程失败: {str(e)}") + return f"选品流程失败,请稍后重试。
错误信息: {str(e)}
" + + def run(self): + """运行智能助手""" + print("跨境汽配选品智能助手已启动!") + print("您可以输入问题或需求,我将为您提供专业的选品建议。") + print("输入 'exit' 或 'quit' 退出程序。") + + while True: + try: + user_input = input("\n您: ") + + if user_input.lower() in ["exit", "quit", "bye"]: + print("再见!感谢使用跨境汽配选品智能助手。") + break + + if not user_input.strip(): + print("请输入有效的问题或需求。") + continue + + print("正在为您分析...") + response = self.chat_process(user_input) + print("\n助手: ") + print(response) + + except KeyboardInterrupt: + print("\n再见!感谢使用跨境汽配选品智能助手。") + break + except Exception as e: + print(f"发生错误: {str(e)}") + print("请重试或联系技术支持。") + +if __name__ == "__main__": + agent = CrossBorderAutoPartsAgent() + agent.run() \ No newline at end of file diff --git a/requirements.txt b/requirements.txt new file mode 100644 index 0000000..d119c62 --- /dev/null +++ b/requirements.txt @@ -0,0 +1,18 @@ +lazyllm>=0.1.0 +transformers>=4.30.0 +pydantic>=2.0.0 +requests>=2.31.0 +pandas>=2.0.0 +flask>=2.0.0 +numpy>=1.24.0 +matplotlib>=3.7.0 +openai>=1.0.0 # 用于真实API调用 +tiktoken>=0.5.0 # 用于token计算 +aiohttp>=3.8.0 # 用于异步HTTP请求 +asyncio # 用于异步处理 +torch>=2.0.0 # 本地模型所需 +accelerate>=0.20.0 # 本地模型加速 +sentencepiece>=0.1.99 # 本地模型分词 +protobuf>=3.20.0 # 本地模型依赖 +scipy>=1.10.0 # 本地模型依赖 +modelscope>=1.30.0 # 本地模型下载和管理 \ No newline at end of file diff --git a/web_init.py b/web_init.py new file mode 100644 index 0000000..e440234 --- /dev/null +++ b/web_init.py @@ -0,0 +1,568 @@ +from flask import Flask, render_template_string, request, jsonify +from auto_parts_agent import AutoPartsAgent + +app = Flask(__name__) + +# 创建汽配选品智能助手实例 +agent = AutoPartsAgent() + +# HTML模板 +html_template = ''' + + + + + +基于LazyLLM框架的智能选品顾问,助您开拓全球汽配市场
+基于市场数据和AI分析,为您提供精准的汽配选品建议
+覆盖北美、欧洲、东南亚等主要市场,了解各地消费者偏好
+全面分析产品成本、物流费用和预期利润率,优化定价策略
+深入分析竞争对手和市场机会,找到差异化优势
+基于LazyLLM的智能顾问
+