From c55ad1fd76ff0d6242d03b16a753b8fdff9450ec Mon Sep 17 00:00:00 2001 From: "jinli.yl" Date: Mon, 21 Jul 2025 16:19:48 +0800 Subject: [PATCH] update --- README.md | 5 - .../{simple_agent => react}/quick_start.md | 0 cookbook/react/zhaoan.py | 205 ++++++++++++++++++ cookbook/simple_agent/messages.jsonl | 46 ++-- cookbook/simple_agent/react_demo.py | 80 +++++++ cookbook/simple_agent/your_own_agent.py | 24 -- experiencemaker/llm/openai_compatible_llm.py | 6 +- experiencemaker/op/react/react_v1_op.py | 9 +- 8 files changed, 310 insertions(+), 65 deletions(-) rename cookbook/{simple_agent => react}/quick_start.md (100%) create mode 100644 cookbook/react/zhaoan.py create mode 100644 cookbook/simple_agent/react_demo.py delete mode 100644 cookbook/simple_agent/your_own_agent.py diff --git a/README.md b/README.md index a7e0783e..6ebcda15 100644 --- a/README.md +++ b/README.md @@ -1,10 +1,5 @@ # ExperienceMaker - - - - - # 🌟 What is ExperienceMaker? ExperienceMaker provides agents with robust capabilities for experience generation and reuse. By summarizing agents' past trajectories into experiences, it enables these experiences to be applied to subsequent tasks. diff --git a/cookbook/simple_agent/quick_start.md b/cookbook/react/quick_start.md similarity index 100% rename from cookbook/simple_agent/quick_start.md rename to cookbook/react/quick_start.md diff --git a/cookbook/react/zhaoan.py b/cookbook/react/zhaoan.py new file mode 100644 index 00000000..1ea2a351 --- /dev/null +++ b/cookbook/react/zhaoan.py @@ -0,0 +1,205 @@ +# ========== Standard and Third-party Imports ========== +import os +import time +import json +import psutil +import statistics +import openai +from loguru import logger +from rich.progress import Progress +from Config.config import TaskConfig +from collections import defaultdict +from llm_client.llm_client import LLMClient +from World_client.env_client import EnvClient +from EM_client.em_client import EMClient +from Summarizer.summarizer import summarize_experience, generate_context +from concurrent.futures import ThreadPoolExecutor, as_completed +from tasks.utils import extract_task, insert_context_before_task, get_task_difficulty + +exp_name = "W_0103" +w_id = "w_0102" + +llm_client = LLMClient(api_key="sk-wE5x9PGlWJn3lwlllprnobZqsWhsfxuc47dobxXYTb0LZM0D", base_url="http://8.130.177.212:3000/v1") + +def run_environment_interaction(client, agent, instance_id, max_interactions) -> int: + + output = None + for i in range(max_interactions): + code = agent.next_code_block(output) + action = {"role": "assistant", "content": code} + result = client.step(instance_id, action) + output = result["state"].get('content', '') + + # Terminate early if the environment signals completion + if result.get('is_terminated', False): + print(f"Terminated after {i + 1} turns") + break + return client.evaluate(instance_id) + + +class ReactAgent: + """ + Agent for proposing the next code block, maintaining + conversation history and interacting with the LLM API. + """ + def __init__(self, history, llm_client): + self.history: list[dict] = history # Initial conversation context + self.llm_client = llm_client + + def next_code_block(self, last_execution_output: str | None = None) -> str: + + if last_execution_output is not None: + self.history.append({"role": "user", "content": last_execution_output}) + code = None + max_tries = 3 + sleep_sec = 3 + for attempt in range(max_tries): + try: + time.sleep(sleep_sec) + code = llm_client.call_llm(self.history) + break + except openai.OpenAIError as e: + logger.error(f"Rate limit error in LLM call on attempt: {attempt + 1}/{max_tries}:{str(e)}") + + #Wait 5 seconds before retrying again + if attempt < max_tries - 1: + logger.info(f"Rate limit exceeded, retrying in {sleep_sec * 2} seconds") + time.sleep(sleep_sec * 2) + except Exception as e: + logger.exception(f"Unexpected error in LLM call: {str(e)}") + + if code is None: + logger.error(f"Failed to generate code after all retries.") + self.history.append({"role": "assistant", "content": code}) + return code + +def evaluate_task(task_id: str, count: int, config: TaskConfig) -> dict: + """ + Executes a single task (multiple runs if best_at > 1), records results, returns highest result. + """ + em_client = EMClient(base_url="http://0.0.0.0:8003") + app_client = EnvClient(base_url="http://localhost:9000") + task_difficulty = get_task_difficulty(task_id) + runs = [] + + try: + for i in range(config.best_at): + print("\n\n" + "*" * 20 + f" Task: {count} | {config.sample_size} " + "*" * 20) + # --- New env & agent every run + init_response = app_client.create_instance(config.env_type, task_id) + instance_id = init_response["info"]["instance_id"] + init_content = init_response["state"]["content"] + + if config.run_with_experience: + task_instruction = extract_task(init_content) + enhanced_content = generate_context(em_client, task_instruction, w_id) + prompt = insert_context_before_task(init_content, enhanced_content) + history = [{"role": "user", "content": prompt}] + else: + history = [{"role": "user", "content": init_content}] + + agent = ReactAgent(history, llm_client) + + # Run or evaluate task as per configuration + score = run_environment_interaction(app_client, agent, instance_id, config.max_interactions) + runs.append((score, agent.history.copy(), init_response)) + print(f"Task id: {task_id} | Run #{i + 1} | Score: {score}") + + try: + success = app_client.release_instance(instance_id) + print(f"Instance released: {success}") + except Exception as e: + logger.exception(f"Failed to release {instance_id}: {str(e)}") + + #Find best run + max_score, max_score_history, max_score_init_response = max(runs, key=lambda x: x[0]) + + # Output task run summary to terminal + print(f"task_id: {task_id} \n" + f"difficulty: {task_difficulty} \n" + f"Score: {max_score} out of {[r[0] for r in runs]} \n") + + result = { + 'task_id': task_id, + 'difficulty': task_difficulty, + 'score': max_score + } + + history_dir = f"/Users/seanlu/PycharmProjects/Simple_ReAct/experiments/{exp_name}" + output_filename = os.path.join(history_dir, f"history_{config.experiment_name}_{task_id}.json") + + + os.makedirs(os.path.dirname(output_filename), exist_ok=True) + with open(output_filename, "w") as f: + json.dump(max_score_history, f, indent=2) + + # Save summarized experience for later training or review + if config.create_exp: + experience_dir = f"/Users/seanlu/PycharmProjects/Simple_ReAct/experiments/Experiences/{exp_name}" + experience_filename = os.path.join(experience_dir, f"{task_id}.json") + os.makedirs(os.path.dirname(experience_filename), exist_ok=True) + instruction = extract_task(max_score_init_response["state"]["content"]) + summarize_experience(em_client, instruction, max_score_history , experience_filename, w_id) + return result + + except Exception as e: + logger.exception(f"Exception in evaluate_task for task_id: {task_id}: {str(e)}") + # Return a failure result for error tracking/statistics + return { + "task_id": task_id, + "difficulty": task_difficulty, + "score": 0, + "error": str(e) + } + # Always attempt to release any used environment instance to prevent resource leaks + + +# ========== Parallel Experiment Pipeline ========== +def main(): + # ---- Load experiment configuration, tasks, and dataset ---- + main_app_client = EnvClient(base_url="http://localhost:9000") + env_type = "appworld" + task_ids = main_app_client.get_task_ids(env_type) + sample_size = 57 + experiment_name = exp_name + max_interactions = 35 + all_results = [] + + config = TaskConfig( + experiment_name=experiment_name, max_interactions=max_interactions, sample_size=sample_size, + env_type=env_type, run_with_experience=False, create_exp=False, best_at = 2 + ) + + # ---- Launch N parallel workers for multiprocessing ---- + with ThreadPoolExecutor(max_workers=20) as executor: + futures = [] + for idx, task_id in enumerate(task_ids[:sample_size]): + futures.append(executor.submit(evaluate_task, task_id, idx + 1, config)) + + with Progress() as progress: + task = progress.add_task("[green]Running experiments...", total=sample_size) + for idx, future in enumerate(as_completed(futures)): + result = future.result() + all_results.append(result) + # Log memory usage in progress bar + mem_mb = psutil.Process(os.getpid()).memory_info().rss / (1024 * 1024) + progress.update( + task, + advance=1, + description=f"Mem: {mem_mb:.1f} MB | {len(all_results)}/{sample_size} complete" + ) + + difficulty_scores = defaultdict(list) + for res in all_results: + if 'difficulty' in res and 'score' in res: + difficulty_scores[res['difficulty']].append(res['score']) + + for diff, scores in sorted(difficulty_scores.items()): + avg = statistics.mean(scores) if scores else 0 + print(f"Difficulty {diff}: {len(scores)} tasks, Average Score: {avg}") + + print(f"Overall Average: {statistics.mean([r['score'] for r in all_results])}") + print(f"Best of: {config.best_at}") + +if __name__ == "__main__": + main() diff --git a/cookbook/simple_agent/messages.jsonl b/cookbook/simple_agent/messages.jsonl index 8d19923a..099d8e99 100644 --- a/cookbook/simple_agent/messages.jsonl +++ b/cookbook/simple_agent/messages.jsonl @@ -1,7 +1,15 @@ [ { "role": "user", - "content": "You are a helpful assistant.\nThe current time is 2025-07-18 20:32:04.\nPlease proactively choose the most suitable tool or combination of tools based on the user's question, including python_execute,web_search,terminate etc.\nPlease first think about how to break down the problem into subtasks, what tools and parameters should be used for each subtask, and finally provide the tool call name and parameters.\nTry calling the same tool multiple times with different parameters to obtain information from various perspectives.\nPlease determine the response language based on the language of the user's question.\n\n# User's Question\n分析一下小米公司\n", + "content": "You are a helpful assistant.\nThe current time is 2025-07-21 15:01:21.\nPlease proactively choose the most suitable tool or combination of tools based on the user's question, including python_execute,web_search,terminate etc.\nPlease first think about how to break down the problem into subtasks, what tools and parameters should be used for each subtask, and finally provide the tool call name and parameters.\nTry calling the same tool multiple times with different parameters to obtain information from various perspectives.\nPlease determine the response language based on the language of the user's question.\n\n# User's Question\nAnalyze Xiaomi Corporation\n", + "reasoning_content": "", + "tool_calls": [], + "tool_call_id": "", + "metadata": {} + }, + { + "role": "assistant", + "content": "To analyze Xiaomi Corporation, we can break down the task into several subtasks:\n\n1. **Overview of Xiaomi Corporation**: Gather general information about the company, such as its history, mission, and main products.\n2. **Financial Performance**: Look into the financial health and performance of Xiaomi Corporation, which includes revenue, profit margins, etc.\n3. **Market Position**: Understand Xiaomi's standing in the market compared to its competitors.\n4. **Recent News/Developments**: Collect recent news articles or press releases about Xiaomi to understand any current events affecting the company.\n5. **Future Outlook**: Summarize any strategic plans or forecasts for Xiaomi’s future.\n\nFor each subtask, I will use the appropriate tools and parameters as follows:\n\n### Subtask 1: Overview of Xiaomi Corporation\n- **Tool:** web_search\n- **Parameters:** {\"query\": \"Xiaomi Corporation overview\"}\n\n### Subtask 2: Financial Performance\n- **Tool:** web_search (to find the latest financial reports)\n- **Parameters:** {\"query\": \"Xiaomi Corporation financial performance 2025\"}\n- **Tool:** python_execute (if numerical data needs analysis)\n- **Parameters:** Will be determined based on available data\n\n### Subtask 3: Market Position\n- **Tool:** web_search\n- **Parameters:** {\"query\": \"Xiaomi Corporation market position 2025\"}\n\n### Subtask 4: Recent News/Developments\n- **Tool:** web_search\n- **Parameters:** {\"query\": \"Xiaomi Corporation recent news 2025\"}\n\n### Subtask 5: Future Outlook\n- **Tool:** web_search\n- **Parameters:** {\"query\": \"Xiaomi Corporation future outlook 2025\"}\n\nLet's start with the first subtask.\n\n### Calling Tools for Subtask 1\n\nI will now call the `web_search` function with the query \"Xiaomi Corporation overview\" to gather general information about Xiaomi Corporation.", "reasoning_content": "", "tool_calls": [], "tool_call_id": "", @@ -9,44 +17,20 @@ }, { "role": "user", - "content": "", - "reasoning_content": "好的,用户让我分析一下小米公司。首先,我需要明确用户的需求是什么。他们可能想了解小米的市场表现、财务状况、产品线、竞争地位或者最近的动态。由于问题比较广泛,我需要分步骤来处理。\n\n首先,我应该使用网络搜索工具获取最新的信息。比如搜索小米公司的最新财报数据、市场占有率、主要产品线以及最近的战略动向。可能需要分别用不同的关键词进行搜索,比如“小米公司 财报 2025”、“小米 市场份额 2025”、“小米 产品线”等等。\n\n接下来,可能需要分析收集到的数据。例如,财务数据方面,查看营收、利润、增长率等指标。市场方面,了解其在智能手机、智能家居等领域的表现。同时,竞争对手的情况也很重要,比如与华为、OPPO等品牌的对比。\n\n如果搜索到的数据足够,可能需要用Python进行一些数据分析,比如用python_execute工具处理财务数据,计算增长率、利润率等指标,或者生成简单的统计图表。不过用户提到不要使用matplotlib,所以可能只能进行基础的数据处理和计算。\n\n另外,还需要考虑小米的商业模式,比如其互联网服务收入、硬件销售策略,以及生态链企业的布局。这些信息可能需要通过多个搜索关键词来获取。\n\n最后,整合所有信息,形成一个全面的分析报告,涵盖财务、市场、产品、竞争等方面,并给出总结和可能的未来展望。如果发现某些信息缺失,可能需要进一步搜索补充", - "tool_calls": [], - "tool_call_id": "", - "metadata": {} - }, - { - "role": "user", - "content": "\n以下是小米公司2025年最新财务数据相关的信息(截至2025年第一季度):\n\n1. **营收与利润** \n - 2025年第一季度总营收达**1113亿元**,同比增长47.4%,连续两个季度突破千亿大关。 \n - 经调整净利润**107亿元**,同比增长64.5%,首次突破百亿大关。 \n - 净收入达**109亿元**(去年同期为42亿元)。 \n\n2. **业务板块表现** \n - **智能手机**:中国大陆市占率18.8%,全球出货量4180万台(连续7季度增长);高端手机(4000元以上)市占率9.6%,同比提升2.6个百分点。 \n - **汽车业务**:单季交付量**75,869台**,收入**186亿元**;连续6个月单月交付超2万台,覆盖65城235家门店。 \n - **IoT与生活消费产品**:收入**323亿元**,同比增长58.7%。 \n\n3. **研发投入** \n - 2025年Q1研发支出**67亿元**,同比增长30.1%;未来五年计划研发投入达**2000亿元**。 \n - 自研3nm旗舰SoC芯片“玄戒O1”发布,累计全球专利数超4.3万件。 \n\n4. **其他关键数据** \n - 小米集团-W(01810.HK)股价截至2025年7月18日为**57.000港元**,日成交量54.70亿港元。 \n\n以上信息均来自公开财报及新闻报道,具体数据以官方披露为准。\n\nThink based on the current content and the user's question: Is the current context sufficient to answer the user's question? \n\n- If the current context is not sufficient to answer the user's question, consider what information is missing. \n Re-plan and think about how to break down the missing information into subtasks. \n For each subtask, determine what tools and parameters should be used for the query.\n Please first provide the reasoning process, then give the tool call name and parameters.\n\n- If the current context is sufficient to answer the user's question, use the **terminate** tool.\n Please determine the response language based on the language of the user's question.\n", + "content": "\n**Xiaomi Corporation Overview** \n\nXiaomi Corporation, founded in April 2010, is a consumer electronics and smart manufacturing company listed on the Main Board of the Hong Kong Stock Exchange (July 9, 2018). Its core business focuses on smartphones, smart hardware connected via an IoT platform, and innovative consumer electronics solutions. \n\nKey aspects include: \n1. **Business Growth & Challenges**: Rapid expansion has led to challenges in system performance, fault recovery, and operational costs for critical business systems. \n2. **Technological Advancements**: \n - Adopted **OceanBase**, a distributed database, to upgrade smart manufacturing systems. Pilot systems have operated stably for months, achieving 2-3x performance improvements, high availability, and reduced costs. \n - Developed products like the **Xiaomi TV A Pro 43/55 2025** series, featuring 4K QLED displays, Dolby Vision®, HDR10+, Dolby Atmos®, and integration with Google TV™ for immersive entertainment. \n3. **Product Innovation**: \n - Offers devices such as the **Xiaomi TV Box S (2nd Gen)** with 4K Ultra HD, Dolby Vision®, and DTS-HD audio. \n - Introduced the **Xiaomi Mijia Constant Temperature Electric Kettle** with advanced temperature control and energy efficiency. \n\nXiaomi continues to prioritize smart manufacturing, IoT integration, and high-performance distributed database solutions to support its global market presence.\n\n\n根据知识库中提供的信息,关于 **Xiaomi Corporation(小米集团)2025 年的财务表现**,目前可获取的直接相关内容如下:\n\n---\n\n### **1. 小米 2024 年财报亮点及 2025 年业务展望** \n> **Xiaomi Posts Best Ever Annual Earnings Report, Lifts 2025 Auto** \n> - **财务表现**:小米 2024 年财报刷新年度记录,单季度营收首次突破 **1000 亿元人民币**,创历史最佳年度财报。 \n> - **业务进展**:电动汽车(EV)业务进展迅速,首款车型交付量达到 10 万辆仅用 229 天,而实现交付量翻倍(20 万辆)仅需 110 天,增速显著。 \n> - **2025 年计划**:CEO 雷军对电动汽车业务持乐观态度,计划推出更高性能的“超跑版”车型(hypercar variant),并进一步扩大 EV 市场份额。 \n\n---\n\n### **2. 关键信息总结** \n- **财务增长**:小米 2024 年营收和利润均创历史新高,但具体 2025 年财务数据(如收入、利润率等)未在知识库中披露。 \n- **战略重点**:2025 年核心增长动力来自电动汽车业务扩张及 AIoT 设备(如智能穿戴、智能家居)的持续布局。 \n\n---\n\n### **备注** \n知识库中未包含小米 2025 年全年完整财务数据,上述内容基于 2024 年财报及业务动态的公开信息。如需更详细数据,建议参考小米官方发布的 2025 年年度报告或最新季度财报。 \n\n--- \n以上内容均直接引用自知识库中的原始文本,未进行额外推断。\n\n\nThe following information from the provided context relates to Xiaomi Corporation's market position in 2025: \n\n1. **Financial and Operational Performance**: \n - Xiaomi Group announced its **2024 annual results** on March 18, 2025, with a total revenue of **RMB 365.9 billion** in 2024. \n - The company reported **686 million monthly active users** globally for its smartphones and tablets, and **904.6 million connected IoT devices** as of 2024. \n\n2. **Market Presence**: \n - Xiaomi operates as a leading consumer electronics and smart manufacturing company centered on smartphones, smart hardware, and IoT platforms. \n - The company continues to emphasize innovation, quality, and affordability, aiming to \"allow everyone in the world to enjoy a better life through technology.\" \n\n3. **Strategic Developments**: \n - In March 2025, Xiaomi raised **HKD 42.5 billion** through a share placement (800 million shares), likely supporting its strategic initiatives. \n - Xiaomi entered the electric vehicle sector in 2021 and unveiled a new logo, signaling diversification into emerging markets. \n\n4. **Upcoming Financial Updates**: \n - Xiaomi scheduled its **Q1 2025 earnings release** on May 27, 2025, followed by an investor call to discuss financial performance and future plans. \n\n5. **Global and Regional Market Trends**: \n - While not directly tied to Xiaomi, reports on global markets like Wi-Fi 6 and electric pressure cookers (e.g., projected **CAGR of 3.08%** for the global electric pressure cooker market by 2032) highlight technological trends Xiaomi may leverage. \n\nNo explicit 2025 market share or ranking data is provided in the context, but Xiaomi's focus on AIoT, smartphones, and expansion into automotive suggests a competitive position in key growth areas.\n\n\nHere are the recent 2025 updates about Xiaomi Corporation from the provided context: \n\n### **1. Xiaomi Smart Doorbell 4 Pro Launch (July 20, 2025)** \n- Xiaomi released the **Xiaomi Smart Doorbell 4 Pro** at a discounted price of **¥394** (RMB). \n\n---\n\n### **2. Q1 2025 Financial Results (May 27, 2025)** \n- **Revenue**: ¥111.3 billion (RMB), up **47.4% YoY**. \n- **Adjusted Net Profit**: ¥10.7 billion (RMB), a record high and up **64.5% YoY**. \n- **Key Highlights**: \n - Smartphone business revenue: ¥50.6 billion (RMB), up **8.9% YoY**. \n - IoT and lifestyle products revenue: ¥32.3 billion (RMB), up **58.7% YoY**. \n - EV and AI innovation business revenue: ¥18.6 billion (RMB). \n - **Xiaomi SU7 series** delivered **75,869 units** in Q1 2025. \n - Smartphone shipments in Mainland China reached **18.8% market share** (ranked #1). \n\n---\n\n### **3. Product Launches and Innovations** \n- **Xiaomi SU7 Ultra**: Launch scheduled for **July 2025** with an 835 km range and enhanced safety features. \n- **Xiaomi TV 50-inch 2025 Model**: Priced at **¥1,199** (RMB) on JD.com (as of March 22, 2025). \n- **AI and Chip Development**: \n - Launched the **Xiaomi mo** open-source large model for inference. \n - Released the **3nm flagship smartphone SoC chip Xiaomi Xuanji o1**, ranking among the global leaders in performance. \n\n---\n\n### **4. Strategic Developments** \n- **R&D Investment**: Xiaomi plans to invest **¥200 billion (RMB)** in R&D from 2025–2030, with **¥13.5 billion (RMB)** already spent from 2021–2024. \n- **Global Expansion**: \n - Xiaomi SU7 became the **top-selling model in China above ¥200,000** (price tier). \n - Expanded offline presence to **16,000 Xiaomi Home stores** and **235 EV sales outlets** in Mainland China. \n\n---\n\n### **5. Upcoming Events** \n- **2024 Annual Report Release**: Scheduled for **March 18, 2025**, with an investor call discussing financial performance and future plans. \n\nFor detailed investor updates, visit Xiaomi’s official **Investor Relations website** or review the Q1 2025 earnings call transcript.\n\n\nFrom the provided context: \n\n**小米网络营销的创新之路与突破之策** \n摘要: 当前小米面临多重挑战:智能手机市场增量收窄,友商等竞品加剧竞争;性价比定位制约品牌高端化进程;线下渠道覆盖与服务效率待优化;新生代消费需求向场景化、情感化迁移。未来,网络营销呈多元、智能、个性趋势,小米需加大研发,推出创新产品,发挥营销与产品相辅相成的作用,不断创新,以在网络营销上取得更大成就,为行业发展做贡献。 \n\nThis indicates that Xiaomi's 2025 outlook involves addressing challenges like market saturation, brand premiumization, and offline channel optimization, while focusing on innovation, R&D, and adapting to trends in personalized and intelligent marketing.\n\nThink based on the current content and the user's question: Is the current context sufficient to answer the user's question? \n\n- If the current context is not sufficient to answer the user's question, consider what information is missing. \n Re-plan and think about how to break down the missing information into subtasks. \n For each subtask, determine what tools and parameters should be used for the query.\n Please first provide the reasoning process, then give the tool call name and parameters.\n\n- If the current context is sufficient to answer the user's question, use the **terminate** tool.\n Please determine the response language based on the language of the user's question.\n", "reasoning_content": "", "tool_calls": [], "tool_call_id": "", "metadata": {} }, { - "role": "user", - "content": "", - "reasoning_content": "Okay, let's see. The user asked for an analysis of Xiaomi Company. The assistant provided some financial data from the first quarter of 2025, including revenue, profit, business segment performance, R&D investment, and stock price. But I need to check if this information is sufficient to fully answer the user's question.\n\nFirst, the user's query is broad, so a comprehensive analysis would typically include market position, competitive landscape, product strategies, recent developments, and future outlook. The current context covers financials and some business segments like smartphones, cars, and IoT. However, there's no mention of competitors, market share comparisons, or strategic initiatives beyond what's in the financial report. \n\nThe data provided is up to Q1 2025, but the current date is July 18, 2025. There might be more recent updates or events in the second quarter that aren't included here. Also, the analysis could benefit from information on challenges Xiaomi faces, such as market saturation or supply chain issues. \n\nSince the initial response doesn't cover all these aspects, the assistant should use the web_search tool to gather more information on competitors, recent strategic moves, and any challenges. Additionally, using python_execute could help in analyzing trends or comparing data points if more numerical data is available. The terminate tool isn't appropriate yet because the answer isn't complete.\n", - "tool_calls": [], - "tool_call_id": "", - "metadata": {} - }, - { - "role": "user", - "content": "\n```\n2025年第二季度全球手机市场份额出炉小米、华为各自强势 两大权威市调机构Canalys和IDC先后发布最新数据,公布了2025年第二季度全球、中国市场TOP5智能手机销量及份额排名。 Canalys的数据显示,三星在本季度成功守住了市场领先地位,凭借其Galaxy A系列,占据了19%的市场份额。苹果位列第二,占比16%。\n\n雷军:2025年1月小米手机市场份额中国第2,份额为16.8%。 华为手机登顶了2025年1月中国手机市场,份额为19.5%。\n\n2025年第17周(4月21日至4月27日)中国智能手机市场份额排名中,小米(含子品牌)和华为分列前两位。 一家机构的统计显示,今年第一季度华为在中国市场的份额位列第一,小米紧随其后,苹果的市场份额则大幅下滑,接近跌出前五。 另一家机构的数据则显示,小米以微弱优势领先,华为紧追不舍。\n\n小米行业内部的竞争导致行业内部竞争加剧的原因包括:一是行业增长缓慢,对市场份额的争夺激烈;二是竞争者数量较多,竞争力量大抵相当; 三是竞争对手提供的产品或服务大致相同,或者只少体现不出明显差异; 四是某些企业为了规模经济的利益,扩大生产规模,市场均势被打破,产品大量过剩,企业开始诉诸于削价竞销。\n\n小米行业潜在竞争对手的威胁指那些可能进入行业参与竞争的企业,它们将带来新的生产能力,分享已有的资源和市场份额,结果是行业生产成本上升,市场竞争加剧,产品售价下降,行业利润减少。\n\n2025年各大品牌围绕市场份额展开了激烈争夺,其中华为与小米尤为突出,双方都在力争市场领先地位。 双方高层也频频交锋,不仅在智能手机领域展开较量,在新兴的智能汽车领域同样互不相让。\n```\n\nThink based on the current content and the user's question: Is the current context sufficient to answer the user's question? \n\n- If the current context is not sufficient to answer the user's question, consider what information is missing. \n Re-plan and think about how to break down the missing information into subtasks. \n For each subtask, determine what tools and parameters should be used for the query.\n Please first provide the reasoning process, then give the tool call name and parameters.\n\n- If the current context is sufficient to answer the user's question, use the **terminate** tool.\n Please determine the response language based on the language of the user's question.\n", + "role": "assistant", + "content": "Based on the gathered information through the `web_search` tool, we have obtained a comprehensive analysis of Xiaomi Corporation covering multiple aspects:\n\n### Overview of Xiaomi Corporation\n- **Founded**: April 2010.\n- **Core Business**: Smartphones, smart hardware connected via an IoT platform, and innovative consumer electronics solutions.\n- **Technological Advancements**: Adoption of OceanBase distributed database for smart manufacturing systems, various product innovations including TVs and electric kettles.\n\n### Financial Performance\n- **2024 Annual Results**: Total revenue of RMB 365.9 billion.\n- **Monthly Active Users**: 686 million globally for smartphones and tablets.\n- **Connected IoT Devices**: 904.6 million as of 2024.\n- **Q1 2025 Financial Highlights**:\n - Revenue: ¥111.3 billion (up 47.4% YoY).\n - Adjusted Net Profit: ¥10.7 billion (record high, up 64.5% YoY).\n - Key growth areas include smartphone business, IoT products, and EV innovation.\n\n### Market Position\n- Leading consumer electronics and smart manufacturing company.\n- Focus on innovation, quality, and affordability.\n- Expansion into new markets like electric vehicles with significant delivery milestones.\n\n### Recent News/Developments\n- Launch of **Xiaomi Smart Doorbell 4 Pro**.\n- Introduction of **Xiaomi SU7 series** delivering 75,869 units in Q1 2025.\n- Upcoming launch of **Xiaomi SU7 Ultra** with advanced features.\n- Investment in R&D and global expansion plans.\n\n### Future Outlook\n- Challenges include market saturation, brand premiumization, and offline channel optimization.\n- Strategies involve increased R&D investment, launching innovative products, and adapting to personalized and intelligent marketing trends.\n\nGiven this detailed analysis, I believe the current context is sufficient to answer the user's question about analyzing Xiaomi Corporation.\n\n### Tool Call", "reasoning_content": "", "tool_calls": [], "tool_call_id": "", "metadata": {} }, - { - "role": "user", - "content": "", - "reasoning_content": "Okay, let's see. The user asked for an analysis of Xiaomi Company. The assistant first provided some financial data from Q1 2025, then used web_search to get more info on market share and competition. Now, the latest context includes details about Xiaomi's market position in China and globally, their competition with Huawei and Samsung, and some industry dynamics.\n\nBut is this enough? The user probably wants a comprehensive analysis. The current info covers financials, market share, and competition. However, maybe there's more to consider. For example, what about Xiaomi's product strategy, recent innovations, or their international expansion? Also, the financial data is up to Q1, but the current date is July 2025, so maybe there's Q2 data available. Additionally, understanding Xiaomi's supply chain, partnerships, or any challenges they're facing (like regulatory issues or supply chain problems) could add depth. The assistant might also need to analyze trends in their revenue growth, profit margins, or R&D investments over time. Since the user mentioned using Python for analysis if needed, perhaps some calculations or visualizations (though not using matplotlib) could help. But since the user's question is in Chinese, the response should be in Chinese. The assistant should check if all key aspects are covered. If not, another web_search or python_execute might be needed. However, the current context seems to cover the main points, so maybe it's time to terminate.\n", - "tool_calls": [], - "tool_call_id": "", - "metadata": {} - }, { "role": "user", "content": "Please integrate the context and provide a complete answer to the user's question.\nPlease determine the response language based on the language of the user's question.\n\n# User's Question\n{query}\n", @@ -56,9 +40,9 @@ "metadata": {} }, { - "role": "user", - "content": "以下是小米公司(Xiaomi Corporation)截至2025年7月的综合分析,涵盖财务表现、市场地位、竞争格局及战略方向:\n\n---\n\n### **一、核心财务指标(2025年Q1数据)**\n1. **营收与利润** \n - 总营收:**1113亿元**(同比增长47.4%),连续两季度突破千亿。 \n - 经调整净利润:**107亿元**(同比增长64.5%),首次单季破百亿。 \n - 净收入:**109亿元**(去年同期42亿元)。 \n\n2. **研发投入** \n - 单季研发支出**67亿元**(同比增30.1%),未来五年计划投入**2000亿元**。 \n - 自研3nm旗舰芯片“玄戒O1”发布,累计专利超**4.3万件**。 \n\n---\n\n### **二、市场地位与业务表现**\n1. **智能手机业务** \n - **中国市场**:市占率18.8%,位列第二(华为19.5%);高端手机(4000元以上)市占率9.6%,同比提升2.6个百分点。 \n - **全球市场**:Q1出货量4180万台(连续7季度增长),与三星(19%)、苹果(16%)形成三强格局。 \n\n2. **智能电动汽车** \n - 单季交付量**75,869台**,收入**186亿元**;连续6个月单月交付超2万台,覆盖65城235家门店。 \n\n3. **IoT与生态链** \n - 收入**323亿元**(同比增58.7%),覆盖智能家居、可穿戴设备等领域。 \n\n---\n\n### **三、竞争格局与行业挑战**\n1. **主要竞争对手** \n - **国内**:与华为争夺市场份额(2025年Q1中国手机销量华为第一,小米第二)。 \n - **国际**:与三星、苹果在高端市场激烈竞争(如小米15系列对标iPhone 16)。 \n\n2. **行业风险** \n - **市场饱和**:全球手机需求放缓,品牌间价格战加剧(如苹果市场份额下滑至前五之外)。 \n - **潜在威胁**:新兴品牌(如传音、OPPO)在细分市场的渗透,以及科技巨头跨界竞争(如特斯拉入局汽车)。 \n\n---\n\n### **四、战略方向与未来展望**\n1. **技术驱动** \n - 加大芯片研发(如“玄戒”系列)、AI应用(如小爱同学升级),巩固硬件+软件生态。 \n\n2. **全球化布局** \n - 欧洲、东南亚市场持续扩张,印度市场巩固领先地位(2025年Q1印度市占率25%)。 \n\n3. **生态链拓展** \n - 推动小米汽车、机器人、低轨卫星等新兴业务,构建“人车家全生态”。 \n\n---\n\n### **五、股票表现(截至2025年7月18日)**\n- **股价**:57.000港元,日成交量54.70亿港元。 \n- **市值**:约5000亿港元(全球科技股中游梯队)。 \n\n---\n\n### **总结**\n小米凭借高性价比产品、快速迭代能力及生态链优势,在全球消费电子市场稳居头部。但需警惕行业增速放缓、竞争加剧及供应链波动风险。若能持续突破高端市场(如冲击苹果/三星份额)并加速国际化,有望维持长期增长。", - "reasoning_content": "Okay, let's tackle this. The user asked for an analysis of Xiaomi Company. I need to provide a comprehensive overview based on the information gathered so far.\n\nFirst, the financial data from Q1 2025 shows strong growth in revenue and profit. That's a good start. Then, the market share data indicates that Xiaomi is competing closely with Huawei and Samsung in both China and globally. The recent web search results mention their positions in the second quarter, which is even more up-to-date. \n\nI should structure the analysis into sections: Financial Performance, Market Position, Competitive Landscape, Strategic Initiatives, and Challenges. The financials highlight their revenue growth and profitability. Market position shows they're a top player in China and expanding globally. Competitively, they're up against big names like Samsung and Apple, especially in the high-end market. Their strategic moves into IoT and automotive sectors are key points. \n\nI also need to mention the challenges, like intense competition and market saturation. The potential threats from new entrants and the need for continuous innovation in R&D are important too. The stock performance and future investment plans add depth to the analysis.\n\nWait, did I miss any key points? The user might want to know about Xiaomi's ecosystem, like their smart home devices or partnerships. Also, the mention of their self-developed chip and patents shows their technological focus. The stock price and market capitalization are relevant for investors.\n\nI should ensure the answer is in Chinese, as the user's question was in Chinese. Let me check the latest data again to confirm accuracy. The Q2 data from the web search shows they maintained a strong position, which is positive. The competitive dynamics with Huawei and Samsung are crucial to highlight.\n\nPutting it all together, the response should be structured clearly, covering each aspect with the data provided. Make sure to use the latest figures and mention the sources where applicable. Conclude with a summary of their strengths and potential areas for growth or risk.", + "role": "assistant", + "content": "### Analysis of Xiaomi Corporation\n\n#### Overview\nXiaomi Corporation, founded in April 2010, is a leading consumer electronics and smart manufacturing company listed on the Main Board of the Hong Kong Stock Exchange since July 9, 2018. The company focuses on smartphones, smart hardware connected via an IoT platform, and innovative consumer electronics solutions. Key technological advancements include adopting the OceanBase distributed database for smart manufacturing systems, which has improved performance by 2-3 times and reduced costs. Notable product innovations comprise the Xiaomi TV A Pro series with 4K QLED displays and Dolby Vision®, and the Xiaomi Mijia Constant Temperature Electric Kettle.\n\n#### Financial Performance\nIn 2024, Xiaomi reported its best-ever annual earnings:\n- **Total Revenue**: RMB 365.9 billion.\n- **Monthly Active Users**: 686 million globally for smartphones and tablets.\n- **Connected IoT Devices**: 904.6 million as of 2024.\n\nFor the first quarter of 2025, Xiaomi achieved significant financial milestones:\n- **Revenue**: ¥111.3 billion (up 47.4% YoY).\n- **Adjusted Net Profit**: ¥10.7 billion (record high, up 64.5% YoY).\n- **Smartphone Business Revenue**: ¥50.6 billion (up 8.9% YoY).\n- **IoT and Lifestyle Products Revenue**: ¥32.3 billion (up 58.7% YoY).\n- **EV and AI Innovation Business Revenue**: ¥18.6 billion.\n- **Xiaomi SU7 Series Deliveries**: 75,869 units in Q1 2025.\n\n#### Market Position\nXiaomi holds a competitive position in the global market:\n- Leading manufacturer in smartphones, smart hardware, and IoT platforms.\n- Emphasizes innovation, quality, and affordability to enhance user experience through technology.\n- Expansion into electric vehicles with notable achievements such as delivering 100,000 units within 229 days and doubling that number within 110 days.\n\n#### Recent News/Developments\n- Launched **Xiaomi Smart Doorbell 4 Pro** at a discounted price of ¥394.\n- Introduced **Xiaomi SU7 series**, achieving significant sales figures.\n- Upcoming launch of **Xiaomi SU7 Ultra** with advanced features like an 835 km range.\n- Released the **3nm flagship smartphone SoC chip Xiaomi Xuanji o1**, ranking among global leaders in performance.\n- Plans to invest ¥200 billion in R&D from 2025–2030, building on previous investments.\n\n#### Future Outlook\nXiaomi faces challenges such as market saturation and brand premiumization but aims to overcome these through strategic initiatives:\n- Increased focus on R&D and launching innovative products.\n- Adapting to trends in personalized and intelligent marketing.\n- Expanding offline presence with 16,000 Xiaomi Home stores and 235 EV sales outlets in Mainland China.\n\n### Conclusion\nXiaomi Corporation continues to innovate and expand its footprint across various markets. With solid financial performance, strategic investments in R&D, and a robust pipeline of new products, Xiaomi is well-positioned for future growth despite facing market challenges. \n\n---\n\nThis analysis provides a comprehensive overview of Xiaomi Corporation's current status and future prospects. If you have any specific areas you'd like more details on, feel free to ask!", + "reasoning_content": "", "tool_calls": [], "tool_call_id": "", "metadata": {} diff --git a/cookbook/simple_agent/react_demo.py b/cookbook/simple_agent/react_demo.py new file mode 100644 index 00000000..0710a080 --- /dev/null +++ b/cookbook/simple_agent/react_demo.py @@ -0,0 +1,80 @@ +import json + +import requests +from dotenv import load_dotenv + +load_dotenv() +base_url = "http://0.0.0.0:8001/" +workspace_id = "test_workspace" + + +def run_agent(query: str, dump_messages: bool = False): + query = "Analyze Xiaomi Corporation" + + response = requests.post(url=base_url + "agent", json={"query": query}) + if response.status_code != 200: + print(response.text) + return [] + + response = response.json() + + answer = response["answer"] + print(answer) + + messages = response["messages"] + if dump_messages: + with open("messages.jsonl", "w") as f: + f.write(json.dumps(messages, indent=2, ensure_ascii=False)) + + return messages + + +def run_summary(messages: list, dump_experience: bool = True): + response = requests.post(url=base_url + "summary", json={ + "workspace_id": workspace_id, + "traj_list": [ + {"messages": messages, "score": 1.0} + ] + }) + + if response.status_code != 200: + print(response.text) + return + + response = response.json() + experience_list = response["experience_list"] + if dump_experience: + with open("experience.jsonl", "w") as f: + f.write(json.dumps(experience_list, indent=2, ensure_ascii=False)) + + +def run_retriever(query: str): + response = requests.post(url=base_url + "retriever", json={ + "workspace_id": workspace_id, + "query": query, + }) + + if response.status_code != 200: + print(response.text) + return "" + + response = response.json() + experience_merged: str = response["experience_merged"] + print(f"experience_merged={experience_merged}") + return experience_merged + + +def run_agent_with_experience(query_first: str, query_second: str, dump_experience: bool = True): + messages = run_agent(query=query_second) + run_summary(messages, dump_experience) + experience_merged = run_retriever(query_first) + messages = run_agent(query=f"{experience_merged}\n\nUser Question:\n{query_first}") + return messages + + +if __name__ == "__main__": + query1 = "Analyze Xiaomi Corporation" + query2 = "Analyze the company Tesla." + + # run_agent(query=query1, dump_messages=True) + run_agent_with_experience(query_first=query1, query_second=query2) diff --git a/cookbook/simple_agent/your_own_agent.py b/cookbook/simple_agent/your_own_agent.py deleted file mode 100644 index fe0cd947..00000000 --- a/cookbook/simple_agent/your_own_agent.py +++ /dev/null @@ -1,24 +0,0 @@ -import json - -from dotenv import load_dotenv -from loguru import logger - -from experiencemaker.schema.request import AgentRequest -from experiencemaker.service.experience_maker_client import ExperienceMakerClient - -load_dotenv() - - -def main(): - # query = "Analyze Xiaomi Corporation." - query = "分析一下小米公司" - - client = ExperienceMakerClient() - request = AgentRequest(query=query) - response = client.call_agent(request) - logger.info(response.answer) - with open("messages.jsonl", "w") as f: - f.write(json.dumps([x.model_dump() for x in response.messages], indent=2, ensure_ascii=False)) - -if __name__ == "__main__": - main() diff --git a/experiencemaker/llm/openai_compatible_llm.py b/experiencemaker/llm/openai_compatible_llm.py index 1853a92d..de5beca1 100644 --- a/experiencemaker/llm/openai_compatible_llm.py +++ b/experiencemaker/llm/openai_compatible_llm.py @@ -8,6 +8,7 @@ from openai.types import CompletionUsage from pydantic import Field, PrivateAttr, model_validator from experiencemaker.enumeration.chunk_enum import ChunkEnum +from experiencemaker.enumeration.role import Role from experiencemaker.llm import LLM_REGISTRY from experiencemaker.llm.base_llm import BaseLLM from experiencemaker.schema.message import Message, ToolCall @@ -108,7 +109,10 @@ class OpenAICompatibleBaseLLM(BaseLLM): elif chunk_enum is ChunkEnum.TOOL: tool_calls.append(chunk) - return Message(reasoning_content=reasoning_content, content=answer_content, tool_calls=tool_calls) + return Message(role=Role.ASSISTANT, + reasoning_content=reasoning_content, + content=answer_content, + tool_calls=tool_calls) def stream_print(self, messages: List[Message], tools: List[BaseTool] = None, **kwargs): enter_think = False diff --git a/experiencemaker/op/react/react_v1_op.py b/experiencemaker/op/react/react_v1_op.py index 9f9c28f8..7a1e8d1d 100644 --- a/experiencemaker/op/react/react_v1_op.py +++ b/experiencemaker/op/react/react_v1_op.py @@ -41,6 +41,7 @@ class ReactV1Op(BaseOp): assistant_message: Message = self.llm.chat(messages) else: assistant_message: Message = self.llm.chat(messages, tools=tools) + messages.append(assistant_message) logger.info(f"assistant.{i}.reasoning_content={assistant_message.reasoning_content}\n" f"content={assistant_message.content}\n" @@ -49,16 +50,16 @@ class ReactV1Op(BaseOp): if has_terminate_tool: break - if "terminate" in assistant_message.content: - logger.warning(f"【bugfix】step={i} find terminate content, break.") - has_terminate_tool = True - for tool in assistant_message.tool_calls: if tool.name == "terminate": has_terminate_tool = True logger.info(f"step={i} find terminate tool, break.") break + if not has_terminate_tool and not assistant_message.tool_calls: + logger.warning(f"【bugfix】step={i} no tools, break.") + has_terminate_tool = True + for j, tool_call in enumerate(assistant_message.tool_calls): logger.info(f"submit step={i} tool_calls.name={tool_call.name} argument_dict={tool_call.argument_dict}")