当前位置: 首页 > news >正文

Multi Agents Collaboration OS:专属多智能体构建—基于业务场景流程构建专属多智能体

背景

随着人工智能技术的飞速发展,大型语言模型(LLM)的能力不断突破,单一智能体的能力边界逐渐显现。为了应对日益复杂的现实世界任务,由多个具备不同能力、可以相互协作的智能体组成的多智能体系统 (Multi-Agent System, MAS) 成为了新的研究热点和发展方向。多智能体系统通过模拟团队协作的方式,能够处理更庞大、更精细、更需要多元知识和能力的复杂问题,在自动化办公、智能决策、流程优化等领域展现出巨大的应用潜力。

然而,构建一个高效、稳定且贴合具体业务需求的多智能体系统并非易事。传统的开发方式往往面临以下挑战:

  1. 高定制化门槛:不同的业务场景需要不同的智能体角色、知识背景、数据源以及协作逻辑,导致开发周期长、成本高。

  2. 协作流程定义复杂:如何设计智能体之间的交互方式、信息流转路径、任务分配和结果汇总机制,是确保系统有效运行的关键,也是设计的难点。

  3. 集成与部署困难:将开发好的多智能体系统无缝对接到现有的业务系统、数据平台或报表工具中,需要考虑接口兼容性、数据一致性等问题。

为了解决这些痛点,我们提出了【Multi Agents Collaboration OS:专属多智能体构建—基于业务场景流程构建专属多智能体】—— 一个旨在简化和标准化多智能体系统构建流程的平台。

核心理念是“基于业务场景流程构建专属多智能体”。它允许用户通过描述具体的业务场景和执行流程,来定义所需的多智能体协作体系。平台根据用户输入的描述信息,能够:

智能创建或选用智能体 (Agents):根据任务需求,自动配置或创建具备特定技能(如数据分析、报告撰写、用户交互等)的智能体。

关联数据与知识 (Data & Knowledge):为智能体接入所需的数据库、文件、知识库等信息资源。

编排协作流程 (Workflows):定义智能体之间的交互逻辑、任务依赖关系和整体工作流。用户只需提供业务场景的描述和智能体协作的需求,平台即可完成从智能体创建、数据知识整合到协作流程编排的全过程。

更重要的是,Multi Agents Collaboration OS 可以将为特定业务场景构建好的多智能体协作体系,封装成标准的 API 服务。这意味着,用户可以将这些强大的、具备自主协作能力的“智能体团队”轻松集成到他们现有的业务系统、报表系统、数据分析平台或其他任何需要智能化能力的系统中,极大地提升了业务流程的自动化和智能化水平,实现了 AI 能力的按需赋能。

本篇博客将深入探讨 Multi Agents Collaboration OS 的设计思路、核心功能以及如何利用它来为您的业务场景构建专属的多智能体解决方案。

核心流程及技术模块

“Multi Agents Collaboration OS”平台的核心价值在于其能够根据用户提供的业务场景和流程描述,智能地完成多智能体系统的构建、编排和部署,极大地降低了用户的开发和集成成本。其核心业务流程可以概括为以下几个由平台智能化驱动的关键步骤:

1. 业务场景与流程的智能理解与建模:AI赋能的蓝图绘制

用户通过自然语言描述或结构化输入等方式,向平台提供其业务场景和期望的执行流程。平台利用其强大的语言理解和知识图谱能力:

  • 智能解析业务目标: 平台能够理解用户的意图和期望解决的问题,例如自动化审批流程、智能客户服务、营销活动优化等。
  • 自动化流程建模: 基于用户的描述,平台智能地识别流程中的关键步骤、参与者和数据流转,并将其转化为平台内部可执行的流程模型。这避免了用户手动绘制复杂流程图的繁琐工作。
  • 智能识别协作需求: 平台自动分析流程模型,识别出哪些环节可以通过多智能体协作来提升效率或效果,并初步判断所需的智能体类型和协作模式。
  • 智能识别数据与知识需求: 平台预测各个智能体在执行任务过程中可能需要的数据来源和知识背景,为后续的数据和知识关联奠定基础。

2. 智能体、数据、知识的自动化创建与关联:一键式构建智能基石

基于对业务场景和流程的智能理解,平台能够自动化地完成智能体、数据和知识的准备工作:

  • 智能体创建与选用 (智能体【创建】):
    • 智能角色推荐: 平台根据任务需求智能推荐预置的智能体角色,例如数据分析师、报告生成器、自然语言交互器等。
    • 自动化能力配置: 平台根据角色需求自动配置智能体的核心能力,例如数据处理算法、文本生成模型、对话管理模块等。
    • 动态智能体生成: 对于更 विशिष्ट 的需求,平台能够动态生成具备特定技能的轻量级智能体。
  • 智能数据关联 (数据|业务场景):
    • 智能数据源识别: 平台自动识别用户描述中提及或流程模型中涉及的数据源,并引导用户进行授权连接。
    • 自动化数据Schema映射: 平台智能地将数据源的Schema映射到智能体可理解的数据结构。
    • 智能数据预处理建议: 平台分析数据质量,并为用户提供数据清洗、转换等预处理建议。
  • 智能知识关联 (知识|业务场景):
    • 智能知识库推荐: 平台根据业务场景和智能体角色,智能推荐相关的知识库或知识片段。
    • 自动化知识抽取与嵌入: 平台能够自动地从用户提供的文档或其他知识源中抽取关键信息,并将其嵌入到智能体的知识体系中。

3. 智能协作流程编排 (场景多智能体创建):无需编码的智能协同设计

平台的核心创新在于其能够智能地编排智能体之间的协作流程:

  • 智能协作模式推荐: 平台根据任务特性和智能体能力,智能推荐合适的协作模式,例如任务分解、信息共享、协商协调等。
  • 可视化流程编排: 用户可以通过直观的图形化界面,拖拽和连接智能体节点,定义它们之间的交互顺序、触发条件和数据流转。平台在后台自动生成可执行的协作逻辑。
  • 基于意图的流程定义: 用户只需描述智能体之间的协作意图(例如,“数据分析完成后通知报告生成器”),平台自动完成底层的消息传递和任务调度。
  • 智能冲突解决策略: 平台内置常见的冲突解决策略,并允许用户根据业务需求进行配置。

4. 业务场景多智能体的自动化封装与发布 (业务场景多智能体):一键生成智能API

一旦多智能体协作系统构建完成,平台能够自动化地将其封装成标准的API服务:

  • 自动化API生成: 平台自动生成符合RESTful等标准的API接口,无需用户进行复杂的API开发工作。
  • 自动化API文档生成: 平台自动生成清晰、完整的API文档,包括接口描述、请求参数、响应格式等。
  • 灵活的API管理: 平台提供API的版本控制、权限管理、监控和日志记录等功能。

5. 业务场景多智能体的无缝集成与应用 (场景应用):AI能力的即插即用

通过标准化的API接口,用户可以将构建好的多智能体协作能力无缝地集成到现有的各种业务系统中:

  • 现有业务系统集成: 通过简单的API调用,业务系统可以轻松地利用多智能体的智能决策、自动化执行等能力。
  • 报表系统智能化: 报表系统可以调用数据分析智能体的API,实现更智能的数据洞察和可视化。
  • 数据系统增强: 数据系统可以利用智能体进行自动化数据清洗、集成和治理。
  • 对话系统升级: 对话系统可以集成具备复杂问题解决能力的智能体,提升用户交互体验。

6. 智能场景测试与自动化发布 (场景测试 -> 业务场景发布):保障质量与效率

平台提供智能化的测试和发布流程:

  • 智能测试用例生成: 平台根据业务场景和流程定义,自动生成覆盖各种场景的测试用例。
  • 自动化测试执行: 平台自动执行生成的测试用例,并提供详细的测试报告。
  • 智能性能评估: 平台自动评估多智能体系统的性能指标,例如响应时间、并发处理能力等。
  • 一键式发布: 测试通过后,用户可以一键将多智能体系统发布为可供其他系统调用的API服务。

在这里插入图片描述

业务场景智能体设计

1. 业务场景驱动的智能体规划

平台以用户输入的业务场景为核心,通过解析用户的场景描述,结合现有的智能体资源,自动生成智能体规划。

  • 智能体中心计划:优先匹配现有智能体,分配任务并定义输入参数和期望输出。
def agents_select_process(user_scenario):# 获取知识库的摘要信息with open('c:/Users/liuli/Desktop/multi_agents_system/multi_agents/kg files/kb_info.json', 'r', encoding='utf-8') as file:kb_data = json.load(file)kb_summary = []for entry in kb_data:summary = entry.get('documents_summary', 'No summary available')kb_summary.append({'file_name': entry.get('documents_file_name', 'Unknown'),'summary': summary})# 智能体中心信息with open('C:/Users/liuli/Desktop/multi_agents_system/multi_agents/agents_info/Agents Info.json', 'r', encoding='utf-8') as file:agents_center_info = json.load(file)# 数据库信息with open ('C:/Users/liuli/Desktop/multi_agents_system/multi_agents/data files/data_file.json','r',encoding='utf-8') as file:data_file_info = json.load(file)with open ("C:\\Users\\liuli\\Desktop\\multi_agents_system\\multi_agents\\data files\\database_files_summary\\databese_list_meata_info.json",'r',encoding='utf-8') as file:database_info  = json.load(file)user_scenario = str(user_scenario)agents_center_info = str(agents_center_info)database_info = str(database_info)data_file_info = str(data_file_info)kb_summary = str(kb_summary)llm = ChatOpenAI(temperature=0, model=model_use)messages = [("system","""# Role: Multi-Agent Collaboration System Planning Module (Agent Planning Module)# Context:You are tasked with creating a detailed execution plan based on a user-provided business scenario. You will receive the scenario description along with information about available resources: existing agents, databases, data files, and knowledge base summaries.Your primary goal is to determine the optimal combination of resources needed to address the user's scenario by performing the following planning steps:1.  **Agent Planning (Focus on Decomposition and System Design):*** **1.1. Decompose the Business Scenario:** Analyze the `user_scenario` thoroughly. Break down the overall goal into a logical sequence of smaller, distinct sub-tasks or processing stages. Identify the necessary inputs and expected outputs for each sub-task. *Aim for modularity where each sub-task could potentially be handled by a specialized agent.** **1.2. Map Sub-tasks to Agents (Prioritize Existing):** For each identified sub-task, evaluate the available `agents_center_info` to see if an existing agent possesses the required capabilities and skills.* If an existing agent matches: Add it to the `agents_center_plan`. In the `tasks` field, list the *specific sub-tasks* (from your decomposition) assigned to this agent for this scenario. Define the `expected_output` relevant to these sub-tasks and specify the required `parameters`, considering inputs needed (potentially outputs from previous agents/steps).* **1.3. Design and Plan New Agents for Gaps:** Identify any sub-tasks that cannot be effectively handled by existing agents. For each gap, design a *new, specialized agent*.* Add the new agent definition to the `agents_create_plan`.* Assign a clear, functional `agent_name`.* Write a detailed `description` explaining its specific purpose, core function, the logic or techniques it might employ (e.g., "Performs sentiment analysis using model X", "Validates data schema compliance", "Generates API call based on template"), and its role within the overall agent workflow.* List the specific `tasks` (sub-tasks from the decomposition) it is designed to perform.* Define its `expected_output` clearly (e.g., "JSON object with sentiment scores", "Boolean validation result", "Formatted API request string").* Specify the necessary input `parameters` it requires, noting dependencies on data sources or outputs from other agents in the sequence.* **1.4. Consider Agent Interaction Flow:** While planning, implicitly consider the flow of information and dependencies between agents (both existing and new). Ensure the sequence of agent tasks aligns logically with the decomposed scenario steps to form a coherent workflow.* **1.5 2.  **Data Planning:** must strictly utilize the data resources contained within the user-provided database and data files.* Examine the `user_scenario` and the planned agent tasks to determine data requirements.* Identify relevant databases from `database_info` and data files from `data_file_info`.* List the necessary databases and data files in the `data_plan`, including their names, descriptions, and paths.3.  **Knowledge Base Planning:**must use the knowledge resources provided by the user.* Based on the `user_scenario` and agent tasks, determine if information from the knowledge base is needed.* Identify relevant topics from the `kb_summary`.* List the required topics and a description of the specific `required_content` needed from each topic in the `knowledge_base_plan`.# Task:Generate a plan strictly in JSON format. The structure must conform *exactly* to the example below. Ensure all planning steps (Agents, Data, Knowledge Base) are covered in the output JSON.请**务必**将所有分析结果组织成一个**单一的、有效的 JSON 对象**,严格遵循以下结构。**不要**在 JSON 对象前后添加任何额外的解释、注释或介绍性文字。```json{"scenario_name":"<output a name for the scenario according to the user_scenario_input>","agents_center_plan": [// List of EXISTING agents selected for this scenario{"agent_name": "<name_of_existing_agent>","description": "<description_from_agents_center_info>","tasks": "<specific_tasks_assigned_for_this_scenario>","expected_output": "<expected_output_for_these_tasks>","code_path":"<absolute_path_to_the_code>","parameters": {// Parameters needed by this agent for these tasks, derived from the scenario// e.g., "input_data_path": "/path/to/relevant/file.csv", "target_metric": "accuracy"}}// ... more existing agents if needed],"agents_create_plan": [// List of NEW agents required for this scenario{"agent_name": "<proposed_name_for_new_agent>","description": "<clear_description_of_what_the_new_agent_does>","tasks": "<specific_tasks_the_new_agent_needs_to_perform>","expected_output": "<what_the_new_agent_should_output>","parameters": {// Input parameters the new agent will require// e.g., "data_source": "database_xyz", "analysis_type": "trend_detection"}}// ... more new agents if needed],"data_plan": {"databases": [// List of relevant databases{"database_name": "<database_name>","database_description": "<database_description>","database_file_path": "<database_file_path>"}// ... more databases if needed],"data_files": [// List of relevant data files{"data_file_name": "<data_file_name>","data_file_description": "<data_file_description>","data_file_path": "<data_file_path>"}// ... more data files if needed]},"knowledge_base_plan": [// List of relevant knowledge base topics and needed content{"topic": "<relevant_topic_from_kb_summary>","required_content": "<description_of_specific_information_needed_from_this_topic>"}// ... more topics if needed]}```"""),("human",# Use f-string formatting to insert the dynamic variables clearlyf"""please generate a detailed plan based on the following business scenario and available resources.Scenario:{user_scenario}Resources:- Agents Center Agent tools (agents_center_info): {agents_center_info}- Databases (database_info): {database_info}- data file (data_file_info): {data_file_info}- knowledge base (kb_summary): {kb_summary}Please strictly follow the JSON format defined in the System instructions to generate a complete plan that includes agent planning (distinguishing between using existing agents and creating new ones), data planning, and knowledge base planning.""")]result = llm.invoke(messages)result = result.content# 处理响应中的换行符和空格result = result.replace('```json', '').replace('```', '').strip()#results = json.loads(result)try:results = json.loads(result)except json.JSONDecodeError as e:st.error(f"Failed to parse LLM response as JSON: {e}")st.error(f"LLM Response:\n{result}")results = {"agents_center_plan": [], "agents_create_plan": [], "data_plan": {}, "knowledge_base_plan": []} # Default empty plan on errorreturn results
  • 智能体创建计划:针对未被覆盖的任务,自动设计新智能体,包括功能描述、任务分解、参数需求和代码生成。
def Agent_Auto_Create_plan(query_message):with open("C:\\Users\\liuli\\Desktop\\multi_agents_system\\multi_agents\\code_gen.py", 'r', encoding='gbk', errors='replace') as f:code = f.read()llm = ChatOpenAI(model=model_use,temperature=0.5,max_tokens=32000)  max_iter = 3iter_count = 0last_error = ""while iter_count < max_iter:llm = ChatOpenAI(model=model_use, temperature=0.5, max_tokens=32000)if iter_count == 0:messages_cob = [("system","""You are an agent creation tool. Please create an intelligent agent based on user requirements. The output should include: agent name, description, expected output, and Python code (if input parameters are required, use appropriate parameters). Please follow these steps:-Thoroughly understand user requirements-Retrieve available modules from the code library-Generate agent information,all information must be english language.-Out your response in Json format.-All code content must be in english language.[Important] Ensure that you correctly manage escape characters within the string. Specifically, address any issues with newline characters and quotation marks in the original string. This preprocessing step is necessary to transform the string into a valid JSON format.[Important warning]All operational logic of the Agent is executed through agent_run(). A main function agent_run() must be generated!!![Note]Strict Code Format: Adhere strictly to the following code template when writing:[  import ...# Brief explanation of what this function doesdef get_(path):# Main logic herereturn file_info_dict## agents main function codedef pandas_data_analy(params):# Extract parameters from the dictionaryuser_message = params.get('user_message_for_pandas', "")file_path = params.get('uploaded_file_path_for_pandas', "")OUTPUT_FOLDER = params.get('OUTPUT_FOLDER', "")# Main function logic here# Example: perform data analysis using pandasreturn result............<Note!> The main function must be named agent_run() and must be in dictionary form.# Function to run the main execution function with input parameters <—must be in dictionary form>def agent_run(input_dict):result = pandas_data_analy(input_dict)return result]-If you need to use the services of large models and Agents, please use the following tool code:## llm model config and model reference code:with open('C:\\Users\\liuli\\Desktop\\multi_agents_system\\multi_agents\\agents_info\\model config.json', 'r') as f:config = json.load(f)if 'selected_model' in st.session_state:model_use = st.session_state.selected_modelelse:model_use = 'gemini-2.0-flash-001'model_config = config[model_use]# 设置环境变量os.environ["OPENAI_API_KEY"] = model_config['openai_api_key']  # 设置 OpenAI API Keyos.environ["OPENAI_MODEL_NAME"] = model_config['model_name']  # 设置模型名称(可选)os.environ["OPENAI_API_BASE"] = model_config['openai_api_base']  # 设置 API 地址(可选)-Import the large model service in the following way: llm = ChatOpenAI(model=model_use,temperature=0.2).【Note】Exercise caution when using modules from the code library. If their use is necessary, pay special attention to designing high-quality prompts for their application.【Note】Parameter design should align with the agent's description, ensuring differentiated and meaningful naming conventions.[Important] Ensure that you correctly manage escape characters within the string. Specifically, address any issues with newline characters and quotation marks in the original string. This preprocessing step is necessary to transform the string into a valid JSON format.The final output agent_name needs to be consistent with the agent names mentioned in the user's query (if provided by the user)..Out your response in Json format,Please note, do not output additional information, only output content in JSON format, and the structure should be similar to the following:# Output Format Instructions:Please ensure that all analysis results are organized into a single, valid JSON object, strictly adhering to the following structure. Do not add any extra explanations, comments, or introductory text before or after the JSON object.Important Warning: Keep the agent's code as concise as possible, and other information should be as refined and accurate as possible. The output content must be complete and a valid JSON format, with the total number of characters not exceeding 20,000!=================JSON format example===================```json{  "agent_name": '<agent_name>',"agent_description": '<agent_description>',"agent_expected_output": '<agent_expected_output>',"agent_code": '<agent_code,python>',"agent_input_parameters": '<agent_input_parameters,like:{"prompt": "","BASE_PATH": ""}>'}"""),("human", 'The code library is:' + str(code) + 'You can reference available modules from this code repository. Example of invocation:from code_gen import ..../nThe Agent info is:' + str(query_message) + './nNote:Do not arbitrarily change the relevant information of the agents in the incoming agents info, especially the names of the agents!')]else:# 反馈上一次的错误信息,要求修正messages_cob = [("system","""You are an agent creation tool. Please create an intelligent agent based on user requirements. The output should include: agent name, description, expected output, and Python code (if input parameters are required, use appropriate parameters). Please follow these steps:-Thoroughly understand user requirements-Retrieve available modules from the code library-Generate agent information,all information must be english language.-Out your response in Json format.-All code content must be in english language.[Important] Ensure that you correctly manage escape characters within the string. Specifically, address any issues with newline characters and quotation marks in the original string. This preprocessing step is necessary to transform the string into a valid JSON format.[Important warning]All operational logic of the Agent is executed through agent_run(). A main function agent_run() must be generated!!![Note]Strict Code Format: Adhere strictly to the following code template when writing:[  import ...# Brief explanation of what this function doesdef get_(path):# Main logic herereturn file_info_dict## Main function codedef pandas_data_analy(params):# Extract parameters from the dictionaryuser_message = params.get('user_message_for_pandas', "")file_path = params.get('uploaded_file_path_for_pandas', "")OUTPUT_FOLDER = params.get('OUTPUT_FOLDER', "")# Main function logic here# Example: perform data analysis using pandasreturn result............<># Function to run the main execution function with input parameters <—must be in dictionary form>def agent_run(input_dict):result = pandas_data_analy(input_dict)return result]-If you need to use the services of large models and Agents, please use the following tool code:with open('C:\\Users\\liuli\\Desktop\\multi_agents_system\\multi_agents\\agents_info\\model config.json', 'r') as f:config = json.load(f)if 'selected_model' in st.session_state:model_use = st.session_state.selected_modelelse:model_use = 'gemini-2.0-flash-001'model_config = config[model_use]# 设置环境变量os.environ["OPENAI_API_KEY"] = model_config['openai_api_key']  # 设置 OpenAI API Keyos.environ["OPENAI_MODEL_NAME"] = model_config['model_name']  # 设置模型名称(可选)os.environ["OPENAI_API_BASE"] = model_config['openai_api_base']  # 设置 API 地址(可选)-Import the large model service in the following way: llm = ChatOpenAI(model=model_use,temperature=0.2).【Note】Exercise caution when using modules from the code library. If their use is necessary, pay special attention to designing high-quality prompts for their application.【Note】Parameter design should align with the agent's description, ensuring differentiated and meaningful naming conventions.[Important] Ensure that you correctly manage escape characters within the string. Specifically, address any issues with newline characters and quotation marks in the original string. This preprocessing step is necessary to transform the string into a valid JSON format.The final output agent_name needs to be consistent with the agent names mentioned in the user's query (if provided by the user)..Out your response in Json format,Please note, do not output additional information, only output content in JSON format, and the structure should be similar to the following:# Output Format Instructions:Please ensure that all analysis results are organized into a single, valid JSON object, strictly adhering to the following structure. Do not add any extra explanations, comments, or introductory text before or after the JSON object.Important Warning: Keep the agent's code as concise as possible, and other information should be as refined and accurate as possible. The output content must be complete and a valid JSON format, with the total number of characters not exceeding 20,000!=================JSON format example===================```json{  "agent_name": '<agent_name>',"agent_description": '<agent_description>',"agent_expected_output": '<agent_expected_output>',"agent_code": '<agent_code,python>',"agent_input_parameters": '<agent_input_parameters,like:{"prompt": "","BASE_PATH": ""}>'}"""),("human", f"""The code library is:{str(code)}You can reference available modules from this code repository. Example of invocation:from code_gen import ...The Agent info is:{str(query_message)}.The last generated agent code did not pass the quality check. The error is: {last_error}Please fix the code according to the error and regenerate. Do not change the agent name or other info unless necessary.Note:Do not arbitrarily change the relevant information of the agents in the incoming agents info, especially the names of the agents!""")]print(messages_cob)cob_result_ = llm.invoke(messages_cob)cob_result = cob_result_.contentwith open('C:\\Users\\liuli\\Desktop\\multi_agents_system\\multi_agents\\agents_info\\agent_code_mode.txt', 'w', encoding='utf-8') as f:f.write(cob_result)json_str = cob_result.replace('```json', '').replace('```', '').strip()try:json_data = json.loads(json_str)except Exception as e:last_error = f"JSON decode error: {e}"iter_count += 1continueagent_code = json_data.get("agent_code", "")passed, error_msg = check_python_code_quality_(agent_code)if passed:json_path = os.path.join('C:\\Users\\liuli\\Desktop\\multi_agents_system\\multi_agents\\agents_info', 'agent_code_mode.json')with open(json_path, 'w', encoding='utf-8') as f:json.dump(json_data, f, ensure_ascii=False, indent=4)return json_dataelse:last_error = error_msgiter_count += 1# 如果多次迭代后仍未通过,返回最后一次的结果和错误return {"error": "Agent code generation failed after multiple attempts.", "last_error": last_error, "last_code": agent_code if 'agent_code' in locals() else ""}

2. 数据与知识资源整合

平台支持对业务场景所需的数据和知识资源进行规划和整合:

  • 数据计划:从用户提供的数据库和数据文件中筛选相关资源,生成数据文件和数据库的使用清单。
  • 知识库计划:根据场景需求,提取知识库中的相关主题和内容,辅助智能体任务执行。

3. 创建的智能体进行测试

自动构建一个任务包括智能体的参数,对创建的智能体进行测试。

 st.markdown("---")st.markdown("### 🛠️ Create & Test Agents")if st.session_state.agents_plan['agents_create_plan']:# Ensure session state keys exist for storing generated contentif 'created_agents_results' not in st.session_state:st.session_state.created_agents_results = {}if 'eval_prompts' not in st.session_state:st.session_state.eval_prompts = {}if 'eval_params_str' not in st.session_state:st.session_state.eval_params_str = {}if 'eval_outputs' not in st.session_state:st.session_state.eval_outputs = {}# Create tabs for each agent with better namingagent_tabs = st.tabs([f"Agent: {agent.get('agent_name', f'Unnamed_{i}')}" for i, agent in enumerate(st.session_state.agents_plan['agents_create_plan'])])for idx, (agent_tab, agent_plan_info) in enumerate(zip(agent_tabs, st.session_state.agents_plan['agents_create_plan'])):with agent_tab:agent_name = agent_plan_info.get('agent_name', f'UnnamedAgent_{idx}')st.subheader(f"Agent Overview: {agent_name}")# Overview card with metricscol1, col2 = st.columns([2, 1])with col1:st.markdown(f"""<div class="card" style="height: 240px;"><h1>🧠 {agent_name}</h1><p><b>Description:</b> {agent_plan_info.get('description', 'N/A')}</p><p><b>Tasks:</b> {agent_plan_info.get('tasks', 'N/A')[:50]}...</p></div>""", unsafe_allow_html=True)with col2:st.markdown(f"""<div class="card" style="height: 240px;"><p><b>Expected Output:</b> {agent_plan_info.get('expected_output', 'N/A')[:50]}...</p><p><b>Parameters:</b> {len(agent_plan_info.get('parameters', {}))} fields</p></div>""", unsafe_allow_html=True)st.markdown("#### Agent Code Generation")with st.expander("🛠️ Code Generation", expanded=True):if st.button(f"🧠 Generate Agent Code", key=f"create_btn_{idx}"):with st.spinner("Creating agent..."):try:agent_result = Agent_Auto_Create_plan(str({"agent_name": agent_name,"agent_description": agent_plan_info.get('description', ''),"agent_expected_output": agent_plan_info.get('expected_output', ''),"agent_input_parameters": agent_plan_info.get('parameters', {}),"agent_tasks": agent_plan_info.get('tasks', '')}))st.session_state.created_agents_results[agent_name] = agent_result# Save agent codeagent_file_path = os.path.join('C:\\Users\\liuli\\Desktop\\multi_agents_system\\multi_agents\\agents_info\\agents_auto_code', f"{agent_name}.py")st.session_state.created_agents_results[agent_name]["code_path"] = agent_file_pathwith open(agent_file_path, 'w', encoding='utf-8') as f:f.write(agent_result.get("agent_code", ""))#agent_result_ = st.session_state.created_agents_results[agent_name]except Exception as e:st.error(f"Error creating agent: {str(e)}")st.code(traceback.format_exc())if agent_name in st.session_state.created_agents_results:with open(st.session_state.created_agents_results[agent_name].get("code_path", ""), 'r',encoding='utf-8') as f:st.download_button(label="⬇️ Download Code",data=f.read(),file_name=f"{agent_name}.py",mime="text/x-python")# Show agent code if existsif agent_name in st.session_state.created_agents_results:agent_result_ = st.session_state.created_agents_results[agent_name]st.code(agent_result_.get("agent_code", ""), language='python')# Testing sectionif agent_name in st.session_state.created_agents_results:agent_result = st.session_state.created_agents_results[agent_name]agent_full_info = {"name": agent_name,"description": agent_plan_info.get('description', ''),"output": agent_plan_info.get('expected_output', ''),"params": agent_result.get("agent_input_parameters", {}),"code_path": agent_result.get("code_path", ""),"usage_count": 0}st.markdown("##### 🧪 Testing Created Agent")with st.expander("🧪 Testing Framework", expanded=True):test_col1, test_col2 = st.columns([1, 1])with test_col1:if st.button(f"📝 Generate Test Prompt", key=f"prompt_btn_{idx}"):with st.spinner("Generating test prompt..."):test_prompt = agents_evaluation_prompt_(agent_result.get("agent_code", ""),agent_full_info,st.session_state.data_plan.get('data_files', []),st.session_state.data_plan.get('databases', []))st.session_state.eval_prompts[agent_name] = test_promptst.markdown(st.session_state.eval_prompts.get(agent_name, ""),)with test_col2:if st.button(f"⚙️ Generate Config", key=f"config_btn_{idx}"):with st.spinner("Analyzing requirements..."):config_result = global_config_process(st.session_state.eval_prompts.get(agent_name, ""),agent_full_info,st.session_state.data_plan.get('databases', []),st.session_state.data_plan.get('data_files', []),agent_plan_info.get('parameters', {}))st.session_state.eval_params_str[agent_name] = json.dumps(config_result, indent=2)st.markdown(st.session_state.eval_params_str.get(agent_name, "{}"),)if st.session_state.eval_params_str and st.button(f"🚀 Execute Agent", key=f"exec_btn_{idx}"):with st.spinner("Executing agent..."):try:params = json.loads(st.session_state.eval_params_str.get(agent_name, "{}"))start_time = time.time()result = code_py_exec(agent_full_info['code_path'], params)exec_time = time.time() - start_timest.session_state.eval_outputs[agent_name] = {"timestamp": datetime.now().isoformat(),"parameters": params,"result": result,"execution_time": exec_time}st.success(f"Execution completed in {exec_time:.2f}s ✅")except Exception as e:st.error(f"Execution failed: {str(e)}")st.code(traceback.format_exc())# Results visualizationif agent_name in st.session_state.eval_outputs:result_data = st.session_state.eval_outputs[agent_name]st.markdown("#### 📊 Execution Results")result_tabs = st.tabs(["📈 Summary", "📋 Raw Data", "📉 Analysis"])with result_tabs[0]:# 任务信息st.markdown(f"**Test Task:** {st.session_state.eval_prompts.get(agent_name, '')}")with result_tabs[1]:st.markdown(result_data['result'])with result_tabs[2]:st.json(result_data['parameters'])st.divider()#增加一个条件,全部执行完成后,才可以导出if st.session_state.agents_plan or st.session_state.created_agents_info:st.markdown("#### 📤 Export Combined Agents Info")if st.button("📤 Export Combined Agents Info"):try:output_path = os.path.join('C:\\Users\\liuli\\Desktop\\multi_agents_system\\multi_agents\\agents_info',f'combined_agents_{datetime.now().strftime("%Y%m%d%H%M")}.json')save_combined_agents_info(st.session_state.agents_plan['agents_center_plan'],st.session_state.created_agents_info,output_path)st.session_state.agents_info_output = output_path  # Clear the plan after exportst.success(f"Agents info successfully exported to:\n{output_path}")st.balloons()except Exception as e:st.error(f"Export failed: {str(e)}")st.code(traceback.format_exc())             

4. 智能体协作流程 测试

平台通过任务规划模块,将智能体、数据和知识资源整合为完整的协作流程:

  • 任务分解与执行:将业务场景分解为多步任务,按逻辑顺序分配给智能体执行。
  • 全局参数配置:为每个任务生成全局参数,确保智能体间的高效协作。
  • 流程可视化:通过流程图展示任务执行步骤及智能体交互关系。
 #业务场景流程创建# 业务场景流程测试 - Placeholder for future implementationst.markdown("---")st.subheader("🚦Test the business scenario process")# 不要在 expander 里嵌套 st.status,先收集 prompt 和 task_configexpander = st.expander("Business Scenario Process Testing", expanded=True)with expander:st.info("Business scenario process testing is not yet implemented.")agent_info_list = st.session_state.agents_plan['agents_center_plan'] + st.session_state.agents_plan['agents_create_plan']agent_info = st.session_state.agents_plan['agents_center_plan'] + st.session_state.agents_plan['agents_create_plan']database_info = st.session_state.agents_plan['data_plan']['databases'] + st.session_state.agents_plan['data_plan']['data_files']kb_summary = st.session_state.agents_plan['knowledge_base_plan']if prompt := st.chat_input("Enter your business scenario prompt here:"):task_scenario = f"Base scenario: {st.session_state.uesr_scenario_input }\n Data used info: {database_info}\n Knowledge base info: {kb_summary}\n User's task: {prompt}"st.session_state.messages.append({"role": "user", "content": prompt})with st.chat_message("user",avatar="C:/Users/liuli/Desktop/multi_agents_system/multi_agents/agents_info/icon/icon.png"):st.markdown(f"<h3>Business Scenario Prompt</h3>", unsafe_allow_html=True)st.write(prompt)with st.spinner("Generating task plan..."):time.sleep(1)task_config = task_planning(task_scenario, agent_info_list, 'C:/Users/liuli/Desktop/multi_agents_system/multi_agents/task_excute_output')global_config_ = task_config['task_execution_steps']st.session_state.messages.append({"role": "assistant", "content": '#### Task Planning Result:\n'+str(task_config)})tabs = st.tabs(["Task Planning Flow", "Task Planning JSON"])with tabs[1]:   with st.chat_message("assistant",avatar="C:/Users/liuli/Desktop/multi_agents_system/multi_agents/agents_info/icon/chat_icon.png"):st.markdown(f"<h3>Task Planning</h3>", unsafe_allow_html=True)st.json(task_config)with tabs[0]:with st.chat_message("assistant",avatar="C:/Users/liuli/Desktop/multi_agents_system/multi_agents/agents_info/icon/chat_icon.png"):st.markdown(f"<h3>Task Planning Flow</h3>", unsafe_allow_html=True)nodes, edges, config = create_flowchart(task_config['task_execution_steps'])# 在 Streamlit 中显示流程图agraph(nodes=nodes, edges=edges, config=config)st.session_state.messages.append({"role": "assistant_flow", "content": (nodes, edges, config)})st.success('Task Planning Completed!')# status.update(label="Thinking Completed!", state='complete',expanded=True)  # 修复UnboundLocalError,删除或注释此行if task_config['agents_selection_dict'] != {}:# 任务拆解step_times = {}# 初始化 prompt_out_put,避免 UnboundLocalErrorprompt_out_put = task_scenariowith open(st.session_state.agents_info_output, 'r', encoding='utf-8') as json_file:agent_info = json.load(json_file)# 将 st.status 移到 expander 外部,避免嵌套for step in task_config['task_execution_steps']:with st.spinner(f"Executing Task: {step['action']}..."):#st.status('正在执行任务(Task Execution)...:**Step{}:** {}'.format(step['step'], step['action']), state='running', expanded=True)try:step_start_time = datetime.now()# agent 参数time.sleep(5)global_config_ = global_config(prompt_out_put, agent_info)agent_file = agent_info[step['tool_selection']]['code_path']params = global_config_[step['tool_selection']]agent_out_put = code_py_exec(agent_file, params)print('Step' + str(i) + 'out_put is:' + str(agent_out_put))if i < len(task_config['task_execution_steps']) - 1:time.sleep(5)prompt_out_put = prompt_info_agent(i, task_config['task_execution_steps'][i + 1], str(agent_out_put))print('Step' + str(i) + 'prompt_out_put is:' + prompt_out_put)i += 1step_data = {"step_num": f"step {step['step']}","task": step['action'],"expected_output": step['expected_output'],"global_config_": str(global_config_),"agent_out_put": agent_out_put,"next_step_prompt_info": prompt_out_put}time.sleep(5)task_excute_result = code_excute_output_optimize(str(prompt_out_put), str(step_data))st.session_state.messages.append({"role": "assistant", "content": task_excute_result})time.sleep(5)step_end_time = datetime.now()step_times[step['step']] = (step_end_time - step_start_time).total_seconds()st.markdown(f"**Step {step['step']}**: {step['action']} - Execution Time: {step_times[step['step']]} seconds\n Result: {task_excute_result}")except:# 记录任务失败的原因step_error = traceback.format_exc()st.error(f"Error in Step {step['step']}: {step_error}")

4. 业务场景封装为API

平台支持将业务场景多智能体协作体系封装为标准化API,便于外部系统调用:

  • API端点:提供执行场景、获取智能体信息、获取数据源信息等功能。
  • 动态参数覆盖:支持用户在调用API时覆盖默认参数,实现灵活定制。
  • 文档生成:自动生成API使用说明,包含场景描述、智能体信息、数据资源及调用示例。
##将创建的智能体计划、数据计划、知识计划结合智能体协作体系整合成一个业务场景,可以输出为一个API,其他应用拿到这个API就可以直接调用这个业务场景的智能体协作体系。#将上述场景的智能体计划、数据计划、知识计划结合智能体协作体系整合成一个业务场景智能体协作体系,输出为json文件,包含需要的智能体、数据、知识库信息,方便其他应用调用。st.markdown('---')st.markdown(f"<h3>🛅 Scenario Multi-Agents Collaboration Output</h3>", unsafe_allow_html=True)if st.button("📤 Export Scenario Multi-Agents Collaboration Output"):try:output_path = os.path.join('C:\\Users\\liuli\\Desktop\\multi_agents_system\\multi_agents\\scenario_info',f'scenario_multi_agents_{datetime.now().strftime("%Y%m%d%H%M")}.json')scenario_api_path = os.path.join('C:\\Users\\liuli\\Desktop\\multi_agents_system\\multi_agents\\scenario_multi_agent_co_api',f'{st.session_state.scenario_name}_scenario_api.py')# 组合导出内容scenario_output = {"scenario_name": st.session_state.scenario_name,"scenario_description": st.session_state.uesr_scenario_input,"agents_center_plan": st.session_state.agents_plan.get('agents_center_plan', []),"agents_create_plan": st.session_state.agents_plan.get('agents_create_plan', []),"data_plan": st.session_state.agents_plan.get('data_plan', {}),"knowledge_base_plan": st.session_state.agents_plan.get('knowledge_base_plan', []),"scenario_api_path":scenario_api_path,"agents_info_path": st.session_state.agents_info_output,"scenario_info_path": output_path,'markdown_path': os.path.join('C:\\Users\\liuli\\Desktop\\multi_agents_system\\multi_agents\\scenario_multi_agent_co_api',f'{st.session_state.scenario_name}_scenario_api.md')}with open(output_path, 'w', encoding='utf-8') as f:json.dump(scenario_output, f, ensure_ascii=False, indent=4)st.success(f"Scenario Multi-Agents Collaboration Output exported to:\n{output_path}")st.session_state.scenario_info_output = output_path#展示合并的计划内容st.balloons()# ...existing code...#展示合并的计划内容if st.session_state.scenario_info_output and os.path.exists(st.session_state.scenario_info_output):st.markdown("#### 合并的业务场景多智能体协作体系内容")with open(st.session_state.scenario_info_output, 'r', encoding='utf-8') as f:scenario_data = json.load(f)# 1. 原始 JSON 展示with st.expander("查看原始 JSON", expanded=False):st.json(scenario_data, expanded=False)# 2. 结构化分块展示with st.expander("智能体中心计划 Agents Center Plan", expanded=False):for agent in scenario_data.get("agents_center_plan", []):st.markdown(f"""<div style="border:1px solid #eee;padding:8px;margin-bottom:8px;border-radius:6px;"><b>名称:</b>{agent.get('agent_name','')}<br><b>描述:</b>{agent.get('description','')}<br><b>任务:</b>{agent.get('tasks','')}<br><b>期望输出:</b>{agent.get('expected_output','')}<br><b>参数:</b><code>{json.dumps(agent.get('parameters',{}), ensure_ascii=False)}</code></div>""", unsafe_allow_html=True)with st.expander("新建智能体计划 Agents Create Plan", expanded=False):for agent in scenario_data.get("agents_create_plan", []):st.markdown(f"""<div style="border:1px solid #eee;padding:8px;margin-bottom:8px;border-radius:6px;"><b>名称:</b>{agent.get('agent_name','')}<br><b>描述:</b>{agent.get('description','')}<br><b>任务:</b>{agent.get('tasks','')}<br><b>期望输出:</b>{agent.get('expected_output','')}<br><b>参数:</b><code>{json.dumps(agent.get('parameters',{}), ensure_ascii=False)}</code></div>""", unsafe_allow_html=True)with st.expander("数据与数据库 Data Plan", expanded=False):data_plan = scenario_data.get("data_plan", {})st.markdown("**数据文件**")for file in data_plan.get("data_files", []):st.write(f"📄 {file.get('data_file_name','')} - {file.get('data_file_description','')} ({file.get('data_file_path','')})")st.markdown("**数据库**")for db in data_plan.get("databases", []):st.write(f"🗄️ {db.get('database_name','')} - {db.get('database_description','')} ({db.get('database_file_path','')})")with st.expander("知识库计划 Knowledge Base Plan", expanded=False):for kb in scenario_data.get("knowledge_base_plan", []):st.write(f"🔖 主题:{kb.get('topic','')}  |  所需内容:{kb.get('required_content','')}")# 3. 原始 JSON 字符串展示with st.expander("原始 JSON 字符串", expanded=False):st.code(json.dumps(scenario_data, ensure_ascii=False, indent=2), language="json")except Exception as e:st.info("暂无合并的计划内容可展示。")# 业务场景流程封装成APIst.markdown("#### 🚀 业务场景流程封装成API")# 业务场景流程封装成APIif st.session_state.scenario_info_output and st.button("📤业务场景流程封装成API"):# 获取当前保存的规划文件路径scenario_plan_path = st.session_state.scenario_info_outputagent_info_path = st.session_state.agents_info_outputprint(scenario_plan_path)if not scenario_plan_path or not os.path.exists(scenario_plan_path):st.error("请先导出业务场景多智能体协作体系")return# 显示API文档说明st.markdown("#### 📦 API接口说明")st.markdown("""生成的API包含以下端点:- `POST /run-scenario`:执行完整业务场景- `GET /agents`:获取所有可用智能体信息- `GET /data-sources`:获取所有数据源信息请求示例:```json{"user_prompt": "请生成Q2销售分析报告","override_params": {"SalesAnalysisAgent": {"time_range": "2024-04-01至2024-06-30"}}}```""")# 显示API代码示例(FastAPI实现)with st.expander("🔧 查看API实现代码", expanded=True):api_code = f'''
from fastapi import FastAPI, HTTPException
from pydantic import BaseModel
import json
import os
import re
import traceback
from datetime import datetime
from task_excute import task_planning, code_py_execapp = FastAPI(title="Multi-Agent Business Scenario API",description="基于规划的智能体协作体系执行业务场景",version="1.0.0"
)# 加载场景规划配置SCENARIO_PLAN_PATH = r"{scenario_plan_path}"with open(SCENARIO_PLAN_PATH, 'r', encoding='utf-8') as f:scenario_config = json.load(f)
agents_info_plan_path = r"{agent_info_path}"
#agents_info_plan_path = re.sub(r"\\", r"/", agents_info_plan_path)
with open(agents_info_plan_path, 'r', encoding='utf-8') as f:agent_config = json.load(f)
class ScenarioRequest(BaseModel):user_prompt: stroverride_params: dict = None@app.post("/run-scenario")
async def run_scenario(request: ScenarioRequest):try:# 合并规划配置和用户参数agents_plan = scenario_config["agents_center_plan"] + scenario_config["agents_create_plan"]data_plan = scenario_config["data_plan"]# 构建任务场景描述task_scenario = f"Base scenario: {st.session_state.uesr_scenario_input}\\n"task_scenario += f"Data used info: {{data_plan}}\\n"task_scenario += f"Knowledge base info: {{scenario_config['knowledge_base_plan']}}\\n"task_scenario += f"User's task: {{request.user_prompt}}"# 任务规划task_config = task_planning(task_scenario, agents_plan, 'C:/Users/liuli/Desktop/multi_agents_system/multi_agents/task_excute_output')# 执行任务流程results = []prompt_out_put = task_scenariofor step in task_config.get('task_execution_steps', []):try:# 应用覆盖参数tool_selection = step['tool_selection']if request.override_params and tool_selection in request.override_params:step_params = request.override_params[tool_selection]step.update(step_params)# 生成全局配置global_config_ = global_config(prompt_out_put, agents_plan)# 执行智能体agent_file = agent_config[tool_selection]['code_path']params = global_config_[tool_selection]agent_out_put = code_py_exec(agent_file, params)# 生成下一步提示if step != task_config['task_execution_steps'][-1]:prompt_out_put = prompt_info_agent(step['step'], task_config['task_execution_steps'][step['step']+1], str(agent_out_put))# 优化输出step_data = {{"step_num": f"step {{step['step']}}","task": step['action'],"expected_output": step['expected_output'],"global_config_": str(global_config_),"agent_out_put": agent_out_put,"next_step_prompt_info": prompt_out_put}}task_excute_result = code_excute_output_optimize(str(prompt_out_put), str(step_data))results.append({{"step": step['step'],"action": step['action'],"result": agent_out_put,"optimized_result": task_excute_result}})except Exception as e:results.append({{"step": step.get('step', 'unknown'),"action": step.get('action', ''),"error": str(e),"traceback": traceback.format_exc()}})return {{"status": "success","timestamp": datetime.now().isoformat(),"scenario": {st.session_state.uesr_scenario_input},"user_prompt": request.user_prompt,"execution_results": results}}except Exception as e:return {{"status": "error","message": str(e),"traceback": traceback.format_exc()}}@app.get("/agents")
async def get_agents():"""获取所有可用智能体信息"""return {{"agents": [agent.get('agent_name') for agent in scenario_config["agents_center_plan"] + scenario_config["agents_create_plan"]]}}@app.get("/data-sources")
async def get_data_sources():"""获取所有可用数据源信息"""return {{"data_sources": {{"databases": scenario_config["data_plan"].get("databases", []),"data_files": scenario_config["data_plan"].get("data_files", [])}}}}if __name__ == "__main__":import uvicornuvicorn.run(app, host="0.0.0.0", port=8000)'''st.code(api_code, language='python')scenario_api_code_path = os.path.join('C:\\Users\\liuli\\Desktop\\multi_agents_system\\multi_agents\\scenario_multi_agent_co_api\\', str(st.session_state.scenario_name)+'_scenario_api.py')with open(scenario_api_code_path, 'w', encoding='utf-8') as f:f.write(api_code)st.success("API代码已保存为 `scenario_api.py`")#生成业务场景使用说明文档#scenario_instructions_prompt_(user_scenario_code,user_scenario,agents_center_info,database_info,data_file_info,kb_summary)with st.spinner("Generating API instructions..."):time.sleep(1)markdown =  scenario_instructions_prompt_(api_code,st.session_state.uesr_scenario_input,st.session_state.agents_plan,st.session_state.data_plan['data_files'],st.session_state.data_plan['databases'],st.session_state.knowledge_base_plan)##保存markdown文件为md文件markdown_path = os.path.join('C:\\Users\\liuli\\Desktop\\multi_agents_system\\multi_agents\\scenario_multi_agent_co_api',f'{st.session_state.scenario_name}_scenario_api.md')with open(markdown_path, 'w', encoding='utf-8') as f:f.write(markdown)st.markdown('---')# 显示API启动说明st.markdown("#### ▶️ 启动API服务")st.markdown(f"""1. 将上述代码保存为 `scenario_api.py`2. 安装依赖:```bashpip install fastapi uvicorn```3. 启动服务:```bashpython scenario_api.py```4. 访问文档:[http://localhost:8000/docs](http://localhost:8000/docs)""")st.expander("API使用说明").markdown(markdown,unsafe_allow_html=True)

5. 输出与集成

平台支持将多智能体协作体系导出为JSON文件或API代码,便于集成到用户的业务系统、报表系统或数据系统中。

import streamlit as st
import json
import os
import subprocess  # Add this with other imports
import timedef _get_scenario_name(file_path):"""Extract scenario name from JSON metadata with error handling"""try:with open(file_path, 'r', encoding='utf-8') as f:data = json.load(f)return data.get('scenario_name', 'Unnamed Scenario')except Exception as e:st.error(f"Error reading {os.path.basename(file_path)}: {str(e)}")return 'Unknown Scenario'def scenario_overview_page():st.title("📊 Business Scenario Overview")# 1. Configure scenario directoryscenario_info_dir = "c:/Users/liuli/Desktop/multi_agents_system/multi_agents/scenario_info"# 2. Scan for scenario filestry:scenario_files = sorted([os.path.join(scenario_info_dir, f) for f in os.listdir(scenario_info_dir) if f.endswith('.json') and os.path.isfile(os.path.join(scenario_info_dir, f))], key=os.path.getmtime, reverse=True)except Exception as e:st.error(f"Error scanning directory: {str(e)}")returnif not scenario_files:st.warning("No scenario files found in the scenario_info directory.")return# 3. File selection with metadataselected_file = st.selectbox("Select a Scenario:",options=scenario_files,format_func=lambda x: f"{_get_scenario_name(x)} - {os.path.basename(x)}",help="Select a scenario file to view its details")# 4. Load selected scenariotry:with open(selected_file, 'r', encoding='utf-8') as f:scenario_data = json.load(f)except Exception as e:st.error(f"Error loading scenario file: {str(e)}")return# 5. Original visualization components (unchanged)st.markdown("""<style>...</style>""", unsafe_allow_html=True)  # Keep original CSS# Main scenario cardwith st.container():st.markdown(f"""<div class='scenario-card'><div class='card-header' style='background: linear-gradient(145deg, #0078ff, #0056b3); color: white; padding: 1.5rem; border-radius: 12px;'><h2 style='margin: 0;'>{scenario_data.get('scenario_name', 'Unnamed Scenario')}</h2><p style='margin: 0.5rem 0 0; font-size: 1.1rem;'>{scenario_data.get('scenario_description', '')}</p></div><div style='margin: 20px 0;'><h4 style='color: #0078ff;'>🛠 Core Components</h4><div style='display: flex; flex-wrap: wrap; gap: 10px;'><span class='agent-pill' style='background: rgba(0,120,255,0.1); color: #0078ff; padding: 8px 16px; border-radius: 20px; font-size: 0.9rem;'>🤖 {len(scenario_data['agents_center_plan'])} Agents</span><span class='data-pill' style='background: rgba(0,200,83,0.1); color: #00c853; padding: 8px 16px; border-radius: 20px; font-size: 0.9rem;'>📊 {len(scenario_data['data_plan']['data_files'])} Data Files</span><span class='data-pill' style='background: rgba(123,31,162,0.1); color: #7b1fa2; padding: 8px 16px; border-radius: 20px; font-size: 0.9rem;'>🗄️ {len(scenario_data['data_plan']['databases'])} Databases</span></div></div></div>""", unsafe_allow_html=True)tabs= st.tabs(["Scenario Overview", "Scenario Multi-Agent Collaboration API Instructions","Scenario Multi-Agent Collaboration API Code"])# Scenario Overview section'])# Agents sectionwith tabs[0]:st.header("🧠 Intelligent Agents")cols_agents = st.columns(2)# Custom CSS for enhanced cardsst.markdown("""<style>.agent-card {background: linear-gradient(145deg, #ffffff, #f8f9fa);border-left: 4px solid #0078ff;border-radius: 12px;padding: 1.5rem;margin-bottom: 1.5rem;box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);transition: all 0.2s ease;}.agent-card:hover {transform: translateY(-2px);box-shadow: 0 6px 8px -1px rgba(0, 0, 0, 0.1);}.data-card {background: linear-gradient(145deg, #ffffff, #f8f9fa);border-left: 4px solid #00c853;border-radius: 12px;padding: 1.5rem;margin-bottom: 1.5rem;box-shadow: 0 4px 6px -1px rgba(0, 0, 0, 0.1);transition: all 0.2s ease;}.data-card:hover {transform: translateY(-2px);box-shadow: 0 6px 8px -1px rgba(0, 0, 0, 0.1);}.pill {background: rgba(0,120,255,0.1);color: #0078ff;padding: 4px 12px;border-radius: 20px;font-size: 0.85em;display: inline-flex;align-items: center;gap: 6px;}.file-path {font-family: 'SFMono-Regular', Consolas, monospace;background: rgba(0,0,0,0.05);padding: 4px 8px;border-radius: 4px;font-size: 0.85em;word-break: break-all;}</style>""", unsafe_allow_html=True)for idx, agent in enumerate(scenario_data['agents_center_plan']):with cols_agents[idx % 2]:# Determine agent iconicon_mapping = {"search": "🔍","financial": "💰","data": "📊","output": "📑"}agent_icon = "🤖"for key in icon_mapping:if key in agent['agent_name'].lower():agent_icon = icon_mapping[key]breakst.markdown(f"""<div class='agent-card'><div style='display: flex; align-items: center; gap: 1rem; margin-bottom: 1rem;'><div style='font-size: 2rem;'>{agent_icon}</div><div><h3 style='margin: 0; color: #1a1a1a;'>{agent['agent_name']}</h3><div style='display: flex; gap: 0.5rem; margin-top: 0.5rem;'><span class='pill'><span style='font-weight: 600;'>Tasks:</span> {len(agent['tasks'].split(';'))}</span><span class='pill'><span style='font-weight: 600;'>Version:</span> {os.path.basename(agent['code_path']).split('_')[-1][:8]}</span></div></div></div><p style='color: #444; line-height: 1.6; margin-bottom: 1rem;'>{agent['description']}</p><div class='st-expander'><details style='border: none;'><summary style='cursor: pointer; color: #0078ff; font-weight: 500;'>Show Parameters ▾</summary><pre style='background: #f8f9fa; padding: 1rem; border-radius: 8px; margin-top: 0.5rem;font-size: 0.85em;'>{json.dumps(agent['parameters'], indent=2)}</pre></details></div></div>""", unsafe_allow_html=True)st.header("🛠️ Agent Creation Plan")cols_create_plan = st.columns(2)for idx, agent in enumerate(scenario_data.get('agents_create_plan', [])):with cols_create_plan[idx % 2]:st.markdown(f"""<div class='agent-card' style='border-left-color: #00c853;'><div style='display: flex; align-items: center; gap: 1rem; margin-bottom: 1rem;'><div style='font-size: 2rem;'>🛠️</div><div><h3 style='margin: 0; color: #1a1a1a;'>{agent['agent_name']}</h3><div style='display: flex; gap: 0.5rem; margin-top: 0.5rem;'><span class='pill' style='background: rgba(0,200,83,0.1);'>Creation Plan</span></div></div></div><p style='color: #444; line-height: 1.6; margin-bottom: 1rem;'>{agent['description']}</p><div class='st-expander'><details style='border: none;'><summary style='cursor: pointer; color: #00c853; font-weight: 500;'>Show Details ▾</summary><div style='padding: 1rem; background: #f8f9fa; border-radius: 8px;'><p><strong>Tasks:</strong> {agent['tasks']}</p><p><strong>Expected Output:</strong> {agent['expected_output']}</p><pre style='background: #ffffff; padding: 1rem; border-radius: 8px; margin-top: 0.5rem;font-size: 0.85em;'>{json.dumps(agent['parameters'], indent=2)}</pre></div></details></div></div>""", unsafe_allow_html=True)st.header("📁 Data Resources")cols_data = st.columns(2)for idx, data_file in enumerate(scenario_data['data_plan']['data_files']):with cols_data[idx % 2]:# Determine file type iconfile_ext = os.path.splitext(data_file['data_file_name'])[1].lower()file_icons = {'.csv': '📊','.xlsx': '📑','.xls': '📑','.json': '📄','.sqlite': '🗄️','.db': '🗄️'}file_icon = file_icons.get(file_ext, '📄')st.markdown(f"""<div class='data-card'><div style='display: flex; align-items: center; gap: 1rem; margin-bottom: 1rem;'><div style='font-size: 1.8rem;'>{file_icon}</div><div><h4 style='margin: 0; color: #1a1a1a;'>{data_file['data_file_name']}</h4><p style='color: #666; margin: 0.4rem 0 0; font-size: 0.95em;'>{data_file['data_file_description']}</p></div></div><div style='display: flex; justify-content: space-between; align-items: center;'><span class='file-path'>{data_file['data_file_path']}</span><span class='pill' style='background: rgba(0,200,83,0.1); color: #00c853;'>{file_ext.upper().replace('.', '') or 'DATA'}</span></div></div>""", unsafe_allow_html=True)# Database sectionst.header("📁 Data Resources【DataBase】")# Add database cardscols_db = st.columns(2)for idx, db in enumerate(scenario_data['data_plan']['databases']):with cols_db[idx % 2]:st.markdown(f"""<div class='data-card' style='border-left-color: #7b1fa2;'><div style='display: flex; align-items: center; gap: 1rem; margin-bottom: 1rem;'><div style='font-size: 1.8rem;'>🗄️</div><div><h4 style='margin: 0; color: #1a1a1a;'>{db['database_name']}</h4><p style='color: #666; margin: 0.4rem 0 0; font-size: 0.95em;'>{db['database_description']}</p></div></div><div style='display: flex; justify-content: space-between; align-items: center;'><span class='file-path'>{db['database_file_path']}</span><span class='pill' style='background: rgba(123,31,162,0.1); color: #7b1fa2;'>DATABASE</span></div></div>""", unsafe_allow_html=True)# Note: The CSS styling block remains identical to original# API Instructions sectionwith tabs[2]:st.header("💻 API Code")#打开code文件API_code_path = scenario_data['scenario_api_path']with open(API_code_path, 'r', encoding='utf-8') as f:api_code = f.read()st.code(api_code, language='python')with tabs[1]:st.header("📝 API Instructions")# Get API path from scenario dataapi_path = scenario_data.get('scenario_api_path', '')markdown_path = scenario_data.get('markdown_path', '')# Display API documentation if availableif os.path.exists(markdown_path):with st.expander("API Documentation"):with open(markdown_path, 'r', encoding='utf-8') as f:api_instructions = f.read()st.markdown(api_instructions)else:st.info("No API documentation available for this scenario")st.divider()# API control sectionst.subheader("🔌 API Service Control")# Convert Windows path to absolute pathif api_path and os.path.exists(api_path):normalized_api_path = os.path.normpath(os.path.abspath(api_path))# Status containerstatus_container = st.empty()# API toggle with enhanced controlsif 'api_process' not in st.session_state:st.session_state.api_process = Noneif st.button("Start API Service" if not st.session_state.api_process else "Stop API Service"):if not st.session_state.api_process:# Start API servicetry:status_container.info("🔄 Starting API service...")# Use Popen to maintain process referencest.session_state.api_process = subprocess.Popen(["python", "-m", "uvicorn", f"{os.path.basename(normalized_api_path)[:-3]}:app","--host", "0.0.0.0", "--port", "8000"],cwd=os.path.dirname(normalized_api_path),stdout=subprocess.PIPE,stderr=subprocess.PIPE,text=True,bufsize=1,universal_newlines=True)# Wait for service to initializetime.sleep(3)# Check if process is runningif st.session_state.api_process.poll() is None:status_container.success("✅ API service started successfully!")st.markdown("""API Documentation: [http://localhost:8000/docs](http://localhost:8000/docs)Test API: [http://localhost:8000/agents](http://localhost:8000/agents)""")else:stdout, stderr = st.session_state.api_process.communicate()status_container.error(f"❌ Failed to start API:\n{stderr}")st.session_state.api_process = Noneexcept Exception as e:status_container.error(f"❌ Error starting API: {str(e)}")st.session_state.api_process = Noneelse:# Stop API servicetry:status_container.info("🛑 Stopping API service...")st.session_state.api_process.terminate()st.session_state.api_process.wait(timeout=5)status_container.success("✅ API service stopped successfully")except Exception as e:status_container.error(f"⚠️ Error stopping API: {str(e)}")finally:st.session_state.api_process = None# Show process statusif st.session_state.api_process:st.markdown("""<div class="status-badge" style="color: #28a745; font-weight: bold;">▫️ API Service Running</div>""", unsafe_allow_html=True)# Display API endpointsst.markdown("""**Available Endpoints:**- `POST /run-scenario` - Execute scenario- `GET /agents` - List available agents- `GET /data-sources` - List data sources""")else:st.error("❌ API file not found. Please verify the scenario configuration.")st.code(f"Expected API path: {api_path}")

实践成果

业务场景之一:电商数据分析

user_scenario_input: When building an e-commerce data analysis business process, it begins with multi-source data integration, collecting order data from e-commerce platforms, user behavior logs, traffic channel information, and market competitor data, which are then cleaned and consolidated into a unified database through ETL tools. Based on business objectives, in-depth analysis follows—for example, identifying high-value customer segments using the RFM model, tracking conversion funnel bottlenecks to pinpoint user drop-off points, validating the impact of page redesigns on conversion rates through A/B testing, and forecasting product sales trends with time-series algorithms. Building on these insights, operational strategies are developed: designing targeted marketing campaigns for users with low repurchase rates, optimizing replenishment plans based on inventory turnover ratios and safety stock thresholds, and adjusting promotional pricing dynamically using pricing models. Next, real-time monitoring dashboards are built via visualization tools, generating operational reports that include key metrics such as GMV growth curves, ROI comparisons across channels, and lists of underperforming SKUs, while aligning with product and marketing teams to refine strategies iteratively. Throughout this process, continuous monitoring of gross margin fluctuations and inventory health is critical, leveraging association rule mining to uncover cross-selling opportunities and proactively intervening through machine learning models (e.g., user churn prediction). Ultimately, this forms a closed-loop system of "data collection → insight diagnosis → strategy execution → performance evaluation → iterative optimization," ensuring every decision is grounded in quantifiable feedback to drive balance between user experience, cost control, and profit growth in e-commerce operations.

1.智能体规划

  • 已有的智能体中心的智能体
    在这里插入图片描述

  • 需创建的智能体
    在这里插入图片描述

  • 数据资源规划
    在这里插入图片描述

  • 2.智能体【创建】的创建及测试
    在这里插入图片描述

  • 生成一个任务及参数 测试智能体
    在这里插入图片描述

测试结果

在这里插入图片描述

  • 3.业务场景多智能体测试
    在这里插入图片描述

  • 数据检索

在这里插入图片描述
在这里插入图片描述

  • 4.业务场景多智能体封装成API

  • 业务场景概览
    在这里插入图片描述

  • 业务场景API启动及说明文档
    在这里插入图片描述
    在这里插入图片描述

总结

“Multi Agents Collaboration OS”平台旨在通过利用LLM技术自动生成和管理多智能体系统,从而简化复杂业务场景的自动化和智能化。 该平台的核心在于其能够根据用户提供的业务场景和需求,自动规划智能体的协作方式、生成智能体的代码、并提供测试和部署工具。

平台的创建基础总结:

  • 智能体规划:

  • 平台能够自动分析用户提供的业务场景,并将其分解为多个子任务,然后规划哪些智能体可以执行这些子任务,包括使用现有智能体或创建新的智能体。

  • 智能体生成: 平台可以根据规划自动生成智能体的代码,从而实现智能体的自动化创建。

  • 智能体执行: 平台提供执行智能体代码的环境和接口,支持传入参数并获取执行结果。

  • 平台面临的问题和挑战:

业务场景需要创建智能体的稳定性和鲁棒性限制:

  • 平台生成的智能体代码的质量和稳定性依赖于LLM的能力,可能存在生成错误代码或无法处理复杂场景的情况。

  • 需要进一步研究如何提高生成代码的鲁棒性,例如,通过引入更多的代码验证和测试机制。

业务场景的知识引入,更好的知识可以拓宽业务场景的使用:

  • 平台目前主要依赖于用户提供的数据和知识库信息,如何更有效地整合和利用这些信息,以及如何自动从外部知识源获取信息,是一个挑战。

  • 更好的知识引入可以拓宽平台的使用范围,使其能够处理更广泛的业务场景。

多智能体协作体系的稳定性和鲁棒性:

  • 多智能体之间的协作涉及到复杂的交互和依赖关系,如何确保协作的稳定性和鲁棒性是一个重要的研究方向。

  • 需要开发更强大的协作流程管理和错误处理机制,以应对各种可能出现的异常情况。

相关文章:

  • 网络安全自动化:精准把握自动化边界,筑牢企业安全防
  • Redis的过期设置和策略
  • Java后端程序员学习前端之CSS
  • 深入理解 Redis 的主从、哨兵与集群架构
  • 基于EFISH-SCB-RK3576工控机/SAIL-RK3576核心板的网络安全防火墙技术方案‌(国产化替代J1900的全栈技术解析)
  • DeepSeek-Prover-V2,DeepSeek推出的开源数学推理大模型
  • 【Leetcode 每日一题 - 补卡】1128. 等价多米诺骨牌对的数量
  • 旋转图像(中等)
  • 一套SaaS ERP系统源码,ERP成品系统源代码,基于SpringBoot框架
  • 1.CFD 计算过程概述:有限元仿真与CFD介绍
  • Sim Studio 是一个开源的代理工作流程构建器。Sim Studio 的界面是一种轻量级、直观的方式,可快速构建和部署LLMs与您最喜欢的工具连接
  • Android学习总结之GetX库篇(优缺点)
  • 网络延时 第四次CCF-CSP计算机软件能力认证
  • 10.施工测量
  • 基于SpringBoot + Vue 的火车票订票系统
  • opencv+opencv_contrib+cuda和VS2022编译
  • JavaScript学习教程,从入门到精通, jQuery的高亮显示图像、留言板、元素内容操作知识点及案例代码(36)
  • Gradio全解20——Streaming:流式传输的多媒体应用(4)——基于Groq的带自动语音检测功能的多模态Gradio应用
  • 【codeforces 2070c】二分答案详解
  • Google-chrome版本升级后sogou输入法不工作了
  • 抗战回望16︱《青年生活》《革命青年》:抗战与青年
  • 电商平台集体出手,多措并举助力外贸企业拓内销
  • 一代名伶程砚秋经典影像:一箱旧影,芳华满堂
  • 取消了“仅退款”,商家就可以高枕无忧了吗?
  • 武汉大学新闻与传播学院已由“80后”副院长吴世文主持工作
  • 美乌矿产协议签署被曝“临门一脚”时生变,美方提附加条件