├── .github └── workflows │ ├── docker-image-pull.yml │ └── docker-image.yml ├── .gitignore ├── Dockerfile ├── Dockerfile_frontend ├── Dockerfile_gh ├── LEGAL.md ├── LICENSE.md ├── MANIFEST.in ├── README.md ├── README_zh.md ├── docker-compose.yaml ├── docker_pull_images.sh ├── docs ├── contribution │ ├── contribute_guide.md │ └── contribute_guide_en.md ├── gh_image_to_aliyun_image.md ├── module │ ├── connector_agent.md │ ├── connector_chain.md │ ├── connector_flow.md │ ├── connector_memory.md │ ├── connector_phase.md │ ├── connector_prompt.md │ ├── customed_examples.md │ └── retrieval.md ├── overview │ ├── o1.muagent.md │ ├── o2.agent-flow.md │ └── o3.quick-start.md └── resources │ ├── agent-flow.png │ ├── agent_runtime.png │ ├── aliyun_01.png │ ├── aliyun_02.webp │ ├── aliyun_03.webp │ ├── aliyun_04.webp │ ├── aliyun_05.webp │ ├── aliyun_06.webp │ ├── baseagent.png │ ├── ekg-arch-en.webp │ ├── ekg-arch-zh.webp │ ├── ekg_demo.png │ ├── executoragent.png │ ├── luban.png │ ├── memory manager.webp │ ├── muagent_framework.png │ ├── reactagent.webp │ ├── selectoragent.webp │ └── wechat.png ├── examples ├── ekg_examples │ ├── start.py │ └── who_is_spy_game.py ├── muagent_examples │ ├── baseGroup_example.py │ ├── baseTask_examples.py │ ├── codeGenDoc_example.py │ ├── codeGenTest_example.py │ ├── codeGenTest_example_copy.py │ ├── codeReact_example.py │ ├── codeRetrieval_example.py │ ├── codeToolReact_example.py │ ├── codechat_example.py │ ├── docchat_example.py │ ├── load_codebase.py │ ├── metagpt_example.py │ ├── search_example.py │ └── toolReact_example.py ├── mysql │ ├── init │ │ └── init.sql │ └── mysql.cnf ├── redis-stack.conf ├── start.py ├── stop.py └── test_config.py.example ├── frontend ├── .eslintrc.js ├── .prettierignore ├── .prettierrc ├── .stylelintrc.js ├── .umirc.ts ├── README.md ├── package.json ├── src │ ├── app.ts │ ├── assets │ │ └── .gitkeep │ ├── components │ │ └── .gitkeep │ ├── constants │ │ └── index.tsx │ ├── pages │ │ └── EKG │ │ │ ├── Common │ │ │ ├── Chat │ │ │ │ ├── AgentPrologue │ │ │ │ │ ├── index.tsx │ │ │ │ │ └── style.ts │ │ │ │ ├── ChatContent.tsx │ │ │ │ ├── ChatFooter.tsx │ │ │ │ ├── TemplateCode │ │ │ │ │ ├── index copy.tsx │ │ │ │ │ ├── index.tsx │ │ │ │ │ └── style.ts │ │ │ │ ├── index.tsx │ │ │ │ ├── sseport.ts │ │ │ │ └── style.ts │ │ │ ├── ChatDetail │ │ │ │ ├── index.tsx │ │ │ │ └── style.ts │ │ │ ├── index.tsx │ │ │ └── style.ts │ │ │ ├── Flow │ │ │ ├── components │ │ │ │ ├── AddNodeList.tsx │ │ │ │ ├── ExecutionConditions │ │ │ │ │ ├── index.tsx │ │ │ │ │ └── style.ts │ │ │ │ ├── NodeHeader.tsx │ │ │ │ └── style.ts │ │ │ ├── index.tsx │ │ │ ├── nodes │ │ │ │ ├── BranchNode.tsx │ │ │ │ ├── EndNode.tsx │ │ │ │ ├── StartNode.tsx │ │ │ │ ├── TaskNode.tsx │ │ │ │ └── style.ts │ │ │ ├── store │ │ │ │ └── index.tsx │ │ │ ├── style.ts │ │ │ └── utils │ │ │ │ ├── ChildNodeTemplate.ts │ │ │ │ ├── index.tsx │ │ │ │ ├── random.tsx │ │ │ │ └── typeFlow.tsx │ │ │ ├── NodeTemplate.ts │ │ │ ├── components │ │ │ ├── EKGHeader │ │ │ │ ├── index.tsx │ │ │ │ └── style.ts │ │ │ ├── EditKnowledgeModal │ │ │ │ ├── index.tsx │ │ │ │ └── style.ts │ │ │ ├── NodeDetailModal │ │ │ │ ├── SceneModalInfo.tsx │ │ │ │ ├── index.tsx │ │ │ │ └── style.ts │ │ │ └── SearchNode │ │ │ │ └── index.tsx │ │ │ ├── flow.d.ts │ │ │ ├── index.tsx │ │ │ ├── nodes │ │ │ ├── OperationPlanNode │ │ │ │ ├── index.tsx │ │ │ │ └── style.ts │ │ │ ├── SceneNode │ │ │ │ ├── index.tsx │ │ │ │ └── style.ts │ │ │ └── StartNode │ │ │ │ ├── index.tsx │ │ │ │ └── style.ts │ │ │ ├── service │ │ │ └── index.ts │ │ │ ├── store │ │ │ └── index.tsx │ │ │ ├── style.ts │ │ │ └── utils │ │ │ ├── format.tsx │ │ │ ├── index.ts │ │ │ ├── nodeAction.ts │ │ │ └── userStore.ts │ ├── services │ │ ├── .gitkeep │ │ ├── afs2demo │ │ │ └── opsconvobus │ │ │ │ ├── EkgGraphController.ts │ │ │ │ └── index.ts │ │ ├── nexa │ │ │ ├── EkgProdController.ts │ │ │ ├── PortalAgentOperationController.ts │ │ │ ├── PortalConversationController.ts │ │ │ ├── PortalKnowledgeController.ts │ │ │ └── typings.d.ts │ │ ├── opsgpt │ │ │ ├── ConversationController.ts │ │ │ └── typings.d.ts │ │ └── user.ts │ └── utils │ │ └── .gitkeep ├── tsconfig.json └── typings.d.ts ├── muagent ├── __init__.py ├── agents │ ├── __init__.py │ ├── agent_util.py │ ├── base_agent.py │ ├── functioncall_agent.py │ ├── group_agent.py │ ├── react_agent.py │ ├── single_agent.py │ ├── task_agent.py │ ├── user_agent.py │ └── util.py ├── base_configs │ ├── __init__.py │ ├── env_config.py │ ├── extra_keywords.txt │ └── prompts │ │ ├── __init__.py │ │ ├── agent_selector_template_prompt.py │ │ ├── checker_template_prompt.py │ │ ├── code2doc_template_prompt.py │ │ ├── code2test_template_prompt.py │ │ ├── executor_template_prompt.py │ │ ├── functioncall_template_prompt.py │ │ ├── input_template_prompt.py │ │ ├── intention_template_prompt.py │ │ ├── metagpt_prompt.py │ │ ├── planner_template_prompt.py │ │ ├── qa_template_prompt.py │ │ ├── react_code_prompt.py │ │ ├── react_template_prompt.py │ │ ├── react_tool_code_planner_prompt.py │ │ ├── react_tool_code_prompt.py │ │ ├── react_tool_prompt.py │ │ ├── refine_template_prompt.py │ │ ├── simple_prompts.py │ │ └── summary_template_prompt.py ├── chat │ ├── __init__.py │ ├── agent_chat.py │ ├── base_chat.py │ ├── code_chat.py │ ├── knowledge_chat.py │ ├── llm_chat.py │ ├── search_chat.py │ └── utils.py ├── codechat │ ├── __init__.py │ ├── code_analyzer │ │ ├── __init__.py │ │ ├── code_analyzer.py │ │ ├── code_dedup.py │ │ ├── code_intepreter.py │ │ ├── code_preprocess.py │ │ ├── code_static_analysis.py │ │ └── language_static_analysis │ │ │ ├── __init__.py │ │ │ └── java_static_analysis.py │ ├── code_crawler │ │ ├── __init__.py │ │ ├── dir_crawler.py │ │ └── zip_crawler.py │ ├── code_search │ │ ├── __init__.py │ │ ├── code_search.py │ │ ├── cypher_generator.py │ │ └── tagger.py │ └── codebase_handler │ │ ├── __init__.py │ │ ├── code_importer.py │ │ └── codebase_handler.py ├── connector │ ├── __init__.py │ ├── agents │ │ ├── __init__.py │ │ ├── base_agent.py │ │ ├── executor_agent.py │ │ ├── react_agent.py │ │ └── selector_agent.py │ ├── antflow │ │ ├── __init__.py │ │ └── flow.py │ ├── chains │ │ ├── __init__.py │ │ ├── base_chain.py │ │ └── chains.py │ ├── configs │ │ ├── __init__.py │ │ ├── agent_config.py │ │ ├── chain_config.py │ │ ├── generate_prompt.py │ │ ├── phase_config.py │ │ └── prompt_config.py │ ├── memory │ │ ├── __init__.py │ │ └── hierarchical_memory_manager.py │ ├── memory_manager.py │ ├── message_process.py │ ├── phase │ │ ├── __init__.py │ │ └── base_phase.py │ ├── prompt_manager │ │ ├── __init__.py │ │ ├── extend_manager.py │ │ └── prompt_manager.py │ ├── schema │ │ ├── __init__.py │ │ ├── general_schema.py │ │ ├── memory.py │ │ └── message.py │ └── utils.py ├── db_handler │ ├── __init__.py │ ├── db.py │ ├── graph_db_handler │ │ ├── __init__.py │ │ ├── aliyun_sls_hanlder.py │ │ ├── base_gb_handler.py │ │ ├── geabase_handler.py │ │ ├── nebula_handler.py │ │ └── networkx_handler.py │ ├── sql_db_hanlder │ │ ├── __init__.py │ │ └── sqlalchemy_handler.py │ ├── utils.py │ └── vector_db_handler │ │ ├── __init__.py │ │ ├── chroma_handler.py │ │ ├── local_faiss_handler.py │ │ └── tbase_handler.py ├── ekg_project.py ├── httpapis │ ├── __init__.py │ └── ekg_construct │ │ ├── __init__.py │ │ └── api.py ├── llm_models │ ├── __init__.py │ ├── embeddings │ │ └── __init__.py │ ├── get_embedding.py │ ├── huggingface_embedding.py │ ├── llm_config.py │ ├── llm_shemas.py │ ├── openai_embedding.py │ └── openai_model.py ├── memory_manager │ ├── __init__.py │ ├── base_memory_manager.py │ ├── hierarchical_memory_manager.py │ ├── local_memory_manager.py │ └── tbase_memory_manager.py ├── models │ ├── __init__.py │ ├── base_model.py │ ├── dashscope_model.py │ ├── kimi_model.py │ ├── ollama_model.py │ ├── openai_model.py │ ├── qwen_model.py │ └── yi_model.py ├── project_manager.py ├── prompt_manager │ ├── __init__.py │ ├── base.py │ ├── base_prompt_manager.py │ ├── common_prompt_manager.py │ ├── language │ │ ├── __init__.py │ │ ├── en.py │ │ └── zh.py │ └── util.py ├── retrieval │ ├── __init__.py │ ├── base_retrieval.py │ ├── base_service.py │ ├── document_loaders │ │ ├── __init__.py │ │ ├── json_loader.py │ │ └── jsonl_loader.py │ ├── faiss_db_service.py │ ├── faiss_m.py │ ├── in_memory.py │ ├── service_factory.py │ ├── text_splitter │ │ ├── __init__.py │ │ ├── langchain_splitter.py │ │ └── utils.py │ └── utils.py ├── sandbox │ ├── __init__.py │ ├── basebox.py │ ├── nbclient.py │ └── pycodebox.py ├── schemas │ ├── __init__.py │ ├── agent_config.py │ ├── apis │ │ ├── __init__.py │ │ └── ekg_api_schema.py │ ├── common │ │ ├── __init__.py │ │ ├── actions.py │ │ ├── auto_extract_graph_schema.py │ │ └── log.py │ ├── db │ │ ├── __init__.py │ │ └── db_config.py │ ├── ekg │ │ ├── __init__.py │ │ ├── ekg_create.py │ │ ├── ekg_graph.py │ │ └── ekg_reason.py │ ├── kb │ │ ├── __init__.py │ │ ├── base_schema.py │ │ └── file_schema.py │ ├── memory.py │ ├── message.py │ ├── models │ │ ├── __init__.py │ │ ├── llm_shemas.py │ │ └── model.py │ ├── project_config.py │ └── readme.md ├── service │ ├── __init__.py │ ├── cb_api.py │ ├── ekg_construct │ │ ├── __init__.py │ │ └── ekg_construct_base.py │ ├── ekg_inference │ │ ├── __init__.py │ │ ├── intention_match_rule.py │ │ └── intention_router.py │ ├── ekg_reasoning │ │ ├── __init__.py │ │ └── src │ │ │ ├── __init__.py │ │ │ ├── geabase_handler │ │ │ ├── __init__.py │ │ │ └── geabase_handlerplus.py │ │ │ ├── graph_search │ │ │ ├── __init__.py │ │ │ ├── call_old_fuction.py │ │ │ ├── geabase_search_plus.py │ │ │ ├── graph_search_main.py │ │ │ ├── task_node_agent.py │ │ │ └── task_node_prompt.py │ │ │ ├── graphstructure │ │ │ ├── __init__.py │ │ │ └── graphstrcturesearchfun.py │ │ │ ├── intention_recognition │ │ │ ├── __init__.py │ │ │ └── intention_recognition_tool.py │ │ │ ├── memory_handler │ │ │ ├── __init__.py │ │ │ └── ekg_memory_handler.py │ │ │ ├── question_answer │ │ │ ├── __init__.py │ │ │ └── qa_function.py │ │ │ └── utils │ │ │ ├── __init__.py │ │ │ ├── call_llm.py │ │ │ ├── crypt.py │ │ │ ├── logger.py │ │ │ └── normalize.py │ ├── kb_api.py │ ├── migrate.py │ ├── ui_file_service │ │ ├── __init__.py │ │ ├── code_base_cds.py │ │ ├── document_base_cds.py │ │ └── document_file_cds.py │ └── utils.py ├── tools │ ├── __init__.py │ ├── abnormal_detection.py │ ├── base_tool.py │ ├── cb_query_tool.py │ ├── codechat_tools.py │ ├── docs_retrieval.py │ ├── duckduckgo_search.py │ ├── metrics_query.py │ ├── multiplier.py │ ├── ocr_tool.py │ ├── sandbox.py │ ├── stock_tool.py │ ├── tool_datas │ │ ├── __init__.py │ │ └── stock_data.py │ ├── undercover.py │ ├── weather.py │ ├── werewolf.py │ └── world_time.py └── utils │ ├── __init__.py │ ├── code2doc_util.py │ ├── common_utils.py │ ├── nebula_cp.sh │ ├── path_utils.py │ ├── postprocess.py │ ├── server_utils.py │ └── static │ ├── __init__.py │ ├── favicon.png │ ├── redoc.standalone.js │ ├── swagger-ui-bundle.js │ └── swagger-ui.css ├── requirements.txt ├── runtime ├── .gitignore ├── Dockerfile ├── Dockerfile.no-package ├── bootstrap │ ├── pom.xml │ └── src │ │ └── main │ │ ├── java │ │ └── com │ │ │ └── alipay │ │ │ └── muagent │ │ │ └── bootstrap │ │ │ └── BootstrapApplication.java │ │ └── resources │ │ ├── config │ │ ├── application-default.properties │ │ └── application.properties │ │ ├── log4j2-spring.xml │ │ ├── static │ │ ├── avatar │ │ │ ├── hangang.png │ │ │ ├── hezixuan.png │ │ │ ├── liangjun.png │ │ │ ├── lijing.png │ │ │ ├── nex.png │ │ │ ├── referee.png │ │ │ ├── shenqiang.png │ │ │ ├── wangpeng.png │ │ │ ├── zhangwei.png │ │ │ ├── zhoujie.png │ │ │ ├── zhouxinyi.png │ │ │ └── zhuli.png │ │ └── index.html │ │ └── tools │ │ ├── 1.json │ │ ├── dispatch_position.json │ │ ├── ekg-query.json │ │ ├── qwen110.json │ │ ├── system.llm_query.json │ │ ├── system.select_tool.json │ │ ├── undercover.dispatch_keyword.json │ │ ├── undercover.dispatch_position.json │ │ ├── undercover.judge.json │ │ ├── undercover.lijing.json │ │ ├── undercover.show_key_information.json │ │ ├── undercover.summary.json │ │ ├── undercover.wangpeng.json │ │ ├── undercover.zhangwei.json │ │ ├── werewolf.dispatch_keyword.json │ │ ├── werewolf.dispatch_position.json │ │ ├── werewolf.hangang.json │ │ ├── werewolf.hezixuan.json │ │ ├── werewolf.judge.json │ │ ├── werewolf.liangjun.json │ │ ├── werewolf.shenqiang.json │ │ ├── werewolf.summary.json │ │ ├── werewolf.zhoujie.json │ │ ├── werewolf.zhouxinyi.json │ │ └── werewolf.zhuli.json ├── model │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── alipay │ │ └── muagent │ │ └── model │ │ ├── agent │ │ └── Agent.java │ │ ├── chat │ │ ├── ChatContent.java │ │ ├── ChatRequest.java │ │ ├── ChatResponse.java │ │ ├── SessionCreateRequest.java │ │ └── content │ │ │ ├── JsonContent.java │ │ │ ├── RoleResponseContent.java │ │ │ └── TextContent.java │ │ ├── connector │ │ └── http │ │ │ └── HttpParameters.java │ │ ├── ekg │ │ ├── BaseEkgResponse.java │ │ ├── EkgAlgorithmResult.java │ │ ├── EkgFeaturesRequest.java │ │ ├── EkgNode.java │ │ ├── EkgNodeType.java │ │ ├── EkgQueryRequest.java │ │ ├── EkgQuestionContent.java │ │ ├── EkgQuestionDescription.java │ │ ├── EkgRequest.java │ │ ├── EkgResponse.java │ │ ├── EkgResponseResultMap.java │ │ ├── EkgSceneSessionRequest.java │ │ ├── EkgToolResponse.java │ │ ├── ExeNodeResponse.java │ │ ├── configuration │ │ │ └── Config.java │ │ └── storage │ │ │ ├── GraphEdge.java │ │ │ ├── GraphGraph.java │ │ │ ├── GraphNode.java │ │ │ └── GraphUpdateRequest.java │ │ ├── enums │ │ ├── chat │ │ │ ├── ChatExtendedKeyEnum.java │ │ │ ├── ChatTypeBelongingTypeEnum.java │ │ │ └── ChatTypeEnum.java │ │ ├── ekg │ │ │ └── ToolPlanTypeEnum.java │ │ ├── refactor │ │ │ └── ResultCodeEnum.java │ │ ├── scheduler │ │ │ └── TaskSchedulerTypeEnum.java │ │ └── tool │ │ │ └── ToolProtocolEnum.java │ │ ├── exception │ │ ├── BizException.java │ │ └── EkgToolNotFindException.java │ │ ├── scheduler │ │ ├── SubmitTaskRequest.java │ │ └── TaskExeResponse.java │ │ ├── shell │ │ ├── ShellRequest.java │ │ └── ShellResponse.java │ │ ├── tool │ │ ├── TaskExeContext.java │ │ ├── ToolExeRequest.java │ │ ├── ToolExeResponse.java │ │ ├── ToolInvokeResponse.java │ │ ├── callback │ │ │ └── CallBackConfig.java │ │ └── meta │ │ │ ├── ApiIvkSchema.java │ │ │ ├── ApiIvkSchemaInfo.java │ │ │ ├── ApiIvkSchemaServer.java │ │ │ ├── ManifestSchema.java │ │ │ ├── Protocol.java │ │ │ ├── ProtocolParameter.java │ │ │ ├── ProtocolSchema.java │ │ │ ├── Protocols.java │ │ │ ├── Tool.java │ │ │ ├── ToolDef.java │ │ │ ├── ToolDefParam.java │ │ │ └── serilizer │ │ │ ├── JsonObjectDeserializer.java │ │ │ └── JsonObjectSerializer.java │ │ └── trace │ │ ├── TraceContext.java │ │ ├── TraceThreadLocalContext.java │ │ └── TraceThreadLocalContextHolder.java ├── pom.xml ├── service │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── alipay │ │ └── muagent │ │ └── service │ │ ├── agent │ │ ├── AgentService.java │ │ └── impl │ │ │ └── AgentServiceImpl.java │ │ ├── chat │ │ ├── ChatService.java │ │ ├── configuration │ │ │ └── EkgConfiguration.java │ │ └── impl │ │ │ ├── EkgChatServiceImpl.java │ │ │ └── MockChatServiceImpl.java │ │ ├── connector │ │ ├── Connector.java │ │ ├── ConnectorManager.java │ │ └── impl │ │ │ ├── GroovyConnector.java │ │ │ └── HttpConnector.java │ │ ├── ekgmanager │ │ ├── EkgGraphManager.java │ │ ├── EkgGraphStorageClient.java │ │ └── impl │ │ │ ├── EkgGraphManagerImpl.java │ │ │ └── EkgGraphStorageClientImpl.java │ │ ├── mybatisplus │ │ ├── dto │ │ │ ├── Converter.java │ │ │ ├── ToolConverter.java │ │ │ ├── ToolDO.java │ │ │ └── ToolJson.java │ │ └── mapper │ │ │ └── ToolDoMapper.java │ │ ├── sheduler │ │ ├── Scheduler.java │ │ ├── SchedulerManager.java │ │ └── impl │ │ │ └── BaseScheduler.java │ │ ├── shell │ │ ├── ShellService.java │ │ └── impl │ │ │ └── ShellServiceImpl.java │ │ ├── thread │ │ └── ThreadPoolConfig.java │ │ └── tool │ │ └── loader │ │ ├── ToolLoader.java │ │ ├── configuration │ │ └── LoaderConfiguration.java │ │ └── impl │ │ ├── LocalToolLoader.java │ │ └── MysqlToolLoader.java ├── util │ ├── pom.xml │ └── src │ │ └── main │ │ └── java │ │ └── com │ │ └── alipay │ │ └── muagent │ │ └── util │ │ ├── GsonUtils.java │ │ ├── HttpUtil.java │ │ ├── LoggerUtil.java │ │ ├── MapUtil.java │ │ ├── StringUtils.java │ │ └── TraceUtil.java └── web │ ├── pom.xml │ └── src │ └── main │ ├── java │ └── com │ │ └── alipay │ │ └── muagent │ │ └── web │ │ ├── AgentController.java │ │ ├── ConversationController.java │ │ ├── EkgStorageController.java │ │ ├── TaskController.java │ │ ├── ToolController.java │ │ ├── base │ │ ├── BaseController.java │ │ └── ControllerProcessor.java │ │ ├── interceptor │ │ ├── RequestInterceptorAspect.java │ │ └── WebConfigure.java │ │ └── model │ │ └── Result.java │ └── resources │ └── spring │ └── spring.xml ├── setup.py └── tests ├── agents ├── funccall_agent_test.py ├── group_agent_test.py ├── react_agent_test.py ├── single_agent_test.py └── task_agent_test.py ├── codechat └── codebasehander_test.py ├── connector ├── agent_test.py ├── chain_test.py ├── flow_test.py ├── hierachical_memory_testy.py ├── memory_manager_test.py └── phase_test.py ├── db_handler ├── geabase_hanlder_test.py ├── nebulahandler_test.py ├── networkx_handler_test.py ├── redis_test.py ├── slshandler_test.py └── tbase_handler_test.py ├── httpapis ├── api_func_test.py ├── api_func_test2.py ├── docker_test.py ├── fastapi_connect_test.py ├── fastapi_connet_test_ekg.py ├── fastapi_connet_test_llm.py ├── fastapi_connet_test_qa.py └── fastapi_test.py ├── llm_models ├── embedding_test.py ├── model_test.py └── openai_test.py ├── memory_manager ├── local_memory_manager_test.py ├── local_mm_crud_test.py └── tbase_memory_manager_test.py ├── orm └── table_test.py ├── prompt_manager ├── base_test.py ├── extend_common_pm_test.py └── new_pm_test.py ├── retrieval ├── faiss_test.py ├── text.txt └── text_splitter_test.py ├── sandbox ├── nbclient_test.py └── sandbox_test.py ├── service ├── EKG_test_construct_data_zq_02.py ├── EKG_test_construct_data_zq_03.py ├── EKG_test_retrieval_one_node.py ├── ekg_construct_test.py ├── ekg_construct_test_2.py ├── ekg_construct_test_2_nebula.py ├── ekg_construct_test_3.py ├── ekg_project_test.py ├── intention_router_test.py ├── test_main_sswd.py └── test_main_sswd_long.py ├── test_config.py.example ├── tools ├── get_tool.py ├── search_test.py └── tool_test.py └── torch_test.py /.github/workflows/docker-image-pull.yml: -------------------------------------------------------------------------------- 1 | name: Docker Image CI Pull 2 | 3 | on: 4 | workflow_dispatch: # 允许手动触发工作流 5 | 6 | jobs: 7 | build: 8 | runs-on: ubuntu-latest 9 | strategy: 10 | matrix: 11 | architecture: [amd64, arm64] 12 | os: [linux] 13 | service: 14 | - name: runtime:0.1.1 15 | - name: muagent:0.1.1 16 | - name: ekgfrontend:0.1.0 17 | 18 | steps: 19 | - name: Checkout code 20 | uses: actions/checkout@v2 21 | 22 | - name: Set up QEMU 23 | uses: docker/setup-qemu-action@v1 24 | 25 | - name: Set up Buildx 26 | uses: docker/setup-buildx-action@v1 27 | 28 | - name: Build the Docker image 29 | run: | 30 | # 登录阿里云镜像仓库 31 | docker login --username=${{ secrets.ALIYUN_USERNAME }} --password=${{ secrets.ALIYUN_PASSWORD }} registry.cn-hangzhou.aliyuncs.com 32 | 33 | # 使用Dockerfile构建镜像 34 | docker pull --platform ${{ matrix.os }}/${{ matrix.architecture }} ghcr.io/codefuse-ai/${{ matrix.service.name }} 35 | docker tag ghcr.io/codefuse-ai/${{ matrix.service.name }} registry.cn-hangzhou.aliyuncs.com/muagent/${{ matrix.service.name }}-${{ matrix.architecture }} 36 | docker push registry.cn-hangzhou.aliyuncs.com/muagent/${{ matrix.service.name }}-${{ matrix.architecture }} -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | **/__pycache__ 2 | knowledge_base 3 | logs 4 | embedding_models 5 | jupyter_work 6 | code_base 7 | data 8 | .DS_Store 9 | .idea 10 | .pyc 11 | test_config.py 12 | package.sh 13 | setup_test.py 14 | build 15 | *egg-info 16 | dist 17 | .ipynb_checkpoints 18 | zdatafront* 19 | *antgroup* 20 | *ipynb 21 | *log 22 | examples/mysql/db 23 | 24 | 25 | 26 | # frontend 27 | frontend/node_modules 28 | frontend/.env.local 29 | frontend/.umirc.local.ts 30 | frontend/config/config.local.ts 31 | frontend/src/.umi 32 | frontend/src/.umi-production 33 | frontend/src/.umi-test 34 | frontend/.umi 35 | frontend/.umi-production 36 | frontend/.umi-test 37 | frontend/dist 38 | frontend/.mfsu 39 | frontend/.swc 40 | frontend/pnpm-lock.yaml 41 | 42 | *.jar 43 | 44 | 45 | 46 | 47 | .spyproject/ 48 | model_config.py 49 | model_config_example.py 50 | config.py 51 | **/service_onlyant 52 | **/ekg_test 53 | **/generalization_reasoning 54 | ekg.yaml 55 | *.ipynb 56 | **/web_operation 57 | examples/mysql/db 58 | tests/service/test_* 59 | tests/service/replacements.py -------------------------------------------------------------------------------- /Dockerfile: -------------------------------------------------------------------------------- 1 | FROM python:3.9-slim-bookworm 2 | 3 | WORKDIR /home/user 4 | 5 | COPY ./requirements.txt /home/user/docker_requirements.txt 6 | 7 | RUN pip config set global.index-url https://pypi.tuna.tsinghua.edu.cn/simple 8 | RUN pip install -r /home/user/docker_requirements.txt --retries 5 --timeout 120 9 | 10 | CMD ["bash"] -------------------------------------------------------------------------------- /Dockerfile_frontend: -------------------------------------------------------------------------------- 1 | FROM node:20.18.0-bookworm 2 | 3 | WORKDIR /home/user 4 | 5 | # 6 | COPY frontend /home/user/frontend 7 | RUN ls /home/user && ls /home/user/frontend 8 | 9 | # 10 | RUN npm config set registry https://registry.npmmirror.com 11 | RUN npm install -g pnpm 12 | RUN pnpm config set registry https://registry.npmmirror.com 13 | # 14 | RUN cd /home/user/frontend && npm i 15 | # 新增删除 16 | RUN cd /home/user/frontend && rm -rf !\(node_modules\) 17 | 18 | CMD ["bash"] -------------------------------------------------------------------------------- /Dockerfile_gh: -------------------------------------------------------------------------------- 1 | FROM python:3.9-slim-bookworm 2 | 3 | WORKDIR /home/user 4 | 5 | COPY ./requirements.txt /home/user/docker_requirements.txt 6 | 7 | RUN pip install -r /home/user/docker_requirements.txt --retries 5 --timeout 120 8 | 9 | CMD ["bash"] -------------------------------------------------------------------------------- /LEGAL.md: -------------------------------------------------------------------------------- 1 | Legal Disclaimer 2 | 3 | Within this source code, the comments in Chinese shall be the original, governing version. Any comment in other languages are for reference only. In the event of any conflict between the Chinese language version comments and other language version comments, the Chinese language version shall prevail. 4 | 5 | 法律免责声明 6 | 7 | 关于代码注释部分,中文注释为官方版本,其它语言注释仅做参考。中文注释可能与其它语言注释存在不一致,当中文注释与其它语言注释存在不一致时,请以中文注释为准。 -------------------------------------------------------------------------------- /MANIFEST.in: -------------------------------------------------------------------------------- 1 | exclude tests/* -------------------------------------------------------------------------------- /docker_pull_images.sh: -------------------------------------------------------------------------------- 1 | #!/bin/bash 2 | 3 | 4 | # while network is error, `docker-compose up -d` might error 5 | # so we add a script for pulling dependent images befort `docker-compose up -d` 6 | 7 | # 国内镜像源,根据需要自行配置,不一定完全生效 8 | # 搜索引擎搜 ”DockerHub国内镜像源列表“ 即可 9 | # "registry-mirrors": [] 10 | 11 | 12 | # pull images from dockerhub docker.io 13 | docker pull vesoft/nebula-metad:v3.8.0 14 | docker pull vesoft/nebula-storaged:v3.8.0 15 | docker pull vesoft/nebula-graphd:v3.8.0 16 | docker pull redis/redis-stack:7.4.0-v0 17 | docker pull ollama/ollama:0.3.6 18 | 19 | # pull images from github ghcr.io by nju 20 | docker pull ghcr.nju.edu.cn/runtime:0.1.1 21 | docker pull ghcr.nju.edu.cn/muagent:0.1.1 22 | docker pull ghcr.nju.edu.cn/ekgfrontend:0.1.0 23 | 24 | # # pull images from github ghcr.io 25 | # docker pull ghcr.io/runtime:0.1.1 26 | # docker pull ghcr.io/muagent:0.1.1 27 | # docker pull ghcr.io/ekgfrontend:0.1.0 28 | -------------------------------------------------------------------------------- /docs/gh_image_to_aliyun_image.md: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## 1、使用google/baidu 搜索 阿里云镜像服务 4 | 5 | ## 2、登录后点击管理控制台 6 | ![](resources/aliyun_01.png) 7 | 8 | ## 3、点击个人实例,如果没有就生成一个(免费的) 9 | ![](resources/aliyun_02.webp) 10 | 11 | ## 4、创建命名空间,取名 muagent,默认私人仓库 12 | ![](resources/aliyun_03.webp) 13 | 14 | ## 5、配置访问凭证 15 | ![](resources/aliyun_04.webp) 16 | 17 | ## 6、fork codefuse-muagent仓库 18 | 19 | ## 7、去fork的仓库settings下配置密钥 20 | ```bash 21 | ALIYUN_USERNAME={见访问凭证处的username} 22 | ALIYUN_PASSWWORD={配置访问凭证} 23 | ``` 24 | ![](resources/aliyun_05.webp) 25 | 26 | ## 8、手动触发将指定镜像同步到个人的阿里云镜像,然后执行本地命令进行拉取阿里云镜像 27 | ![](resources/aliyun_06.webp) 28 | 29 | ```bash 30 | # 本地执行拉取镜像 31 | # 示例,仅支持ekgfrontend、runtime、muagent;其他镜像根据需求对docker-image-pull进行修改 32 | 33 | # 登录阿里云镜像库 34 | docker login --username=xxx registry.cn-hangzhou.aliyuncs.com 35 | 36 | # 拉取amd版本的runtime 37 | docker pull registry.cn-hangzhou.aliyuncs.com/muagent/runtime:0.1.0-amd64 38 | 39 | # 改成docker-compose.yaml 可以直接使用的版本 40 | docker tag registry.cn-hangzhou.aliyuncs.com/muagent/runtime:0.1.0-amd64 runtime:0.1.0 41 | ``` 42 | -------------------------------------------------------------------------------- /docs/overview/o2.agent-flow.md: -------------------------------------------------------------------------------- 1 | --- 2 | title: Agent 编排 3 | slug: Agent 编排 4 | url: "muagent/agent-编排" 5 | aliases: 6 | - "/muagent/agent-编排" 7 | - "/muagent/agent-flow-zh" 8 | --- 9 | 10 | 11 | 12 | ## 核心Connector介绍 13 | 为了便于大家理解整个 muagent 的链路,我们采取 Flow 的形式来详细介绍如何通过配置构建 14 | 15 |
16 | 图片 17 |
18 | 19 | 20 |
下面,我们先介绍相关的核心组件
21 | 22 | ### Agent 23 | 在Agent设计层面,我们提供了四种基本的Agent类型,对这些Agent进行Role的基础设定,可满足多种通用场景的交互和使用 24 | 1. BaseAgent:提供基础问答、工具使用、代码执行的功能,根据Prompt格式实现 输入 => 输出 25 | 26 | 2. ReactAgent:提供标准React的功能,根据问题实现当前任务 27 | 28 | 3. ExecutorAgent:对任务清单进行顺序执行,根据 User 或 上一个Agent编排的计划,完成相关任务 29 | 30 | 4. SelectorAgent:提供选择Agent的功能,根据User 或 上一个 Agent的问题选择合适的Agent来进行回答. 31 | 32 | 33 | 输出后将 message push 到 memory pool 之中,后续通过Memory Manager进行管理 34 | 35 | ### Chain 36 | 基础链路:BaseChain,串联agent的交互,完成相关message和memory的管理 37 | 38 | ### Phase 39 | 基础场景:BasePhase,串联chain的交互,完成相关message和memory的管理 40 | 41 | ### Prompt Manager 42 | Mutli-Agent链路中每一个agent的prompt创建 43 | - 通过对promtp_input_keys和promtp_output_keys对的简单设定,可以沿用预设 Prompt Context 创建逻辑,从而实现agent prompt快速配置 44 | - 也可以对prompt manager模块进行新的 key-context 设计,实现个性化的 Agent Prompt 45 | 46 | ### Memory Manager 47 | 主要用于 chat history 的管理 48 | - 将chat history在数据库进行读写管理,包括user input、 llm output、doc retrieval、code retrieval、search retrieval 49 | - 对 chat history 进行关键信息总结 summary context,作为 prompt context 50 | - 提供检索功能,检索 chat history 或者 summary context 中与问题相关信息,辅助问答 51 | -------------------------------------------------------------------------------- /docs/resources/agent-flow.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/agent-flow.png -------------------------------------------------------------------------------- /docs/resources/agent_runtime.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/agent_runtime.png -------------------------------------------------------------------------------- /docs/resources/aliyun_01.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/aliyun_01.png -------------------------------------------------------------------------------- /docs/resources/aliyun_02.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/aliyun_02.webp -------------------------------------------------------------------------------- /docs/resources/aliyun_03.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/aliyun_03.webp -------------------------------------------------------------------------------- /docs/resources/aliyun_04.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/aliyun_04.webp -------------------------------------------------------------------------------- /docs/resources/aliyun_05.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/aliyun_05.webp -------------------------------------------------------------------------------- /docs/resources/aliyun_06.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/aliyun_06.webp -------------------------------------------------------------------------------- /docs/resources/baseagent.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/baseagent.png -------------------------------------------------------------------------------- /docs/resources/ekg-arch-en.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/ekg-arch-en.webp -------------------------------------------------------------------------------- /docs/resources/ekg-arch-zh.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/ekg-arch-zh.webp -------------------------------------------------------------------------------- /docs/resources/ekg_demo.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/ekg_demo.png -------------------------------------------------------------------------------- /docs/resources/executoragent.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/executoragent.png -------------------------------------------------------------------------------- /docs/resources/luban.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/luban.png -------------------------------------------------------------------------------- /docs/resources/memory manager.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/memory manager.webp -------------------------------------------------------------------------------- /docs/resources/muagent_framework.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/muagent_framework.png -------------------------------------------------------------------------------- /docs/resources/reactagent.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/reactagent.webp -------------------------------------------------------------------------------- /docs/resources/selectoragent.webp: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/selectoragent.webp -------------------------------------------------------------------------------- /docs/resources/wechat.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/docs/resources/wechat.png -------------------------------------------------------------------------------- /examples/mysql/mysql.cnf: -------------------------------------------------------------------------------- 1 | [mysqld] 2 | character-set-server=utf8mb4 3 | collation-server=utf8mb4_unicode_ci 4 | 5 | [client] 6 | default-character-set=utf8mb4 7 | 8 | [mysql] 9 | default-character-set=utf8mb4 -------------------------------------------------------------------------------- /examples/redis-stack.conf: -------------------------------------------------------------------------------- 1 | # https://redis.io/docs/latest/operate/oss_and_stack/management/config-file/ 2 | 3 | # disable rdb 4 | save "" 5 | 6 | # aof config 7 | appendonly yes 8 | appendfsync everysec 9 | auto-aof-rewrite-min-size 8mb -------------------------------------------------------------------------------- /examples/stop.py: -------------------------------------------------------------------------------- 1 | import docker, sys, os 2 | from loguru import logger 3 | 4 | src_dir = os.path.join( 5 | os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 6 | ) 7 | 8 | DEFAULT_BIND_HOST = "127.0.0.1" 9 | os.environ["DEFAULT_BIND_HOST"] = DEFAULT_BIND_HOST 10 | CONTRAINER_NAME = "muagent" 11 | IMAGE_NAME = "devopsgpt:py39" 12 | SANDBOX_CONTRAINER_NAME = "devopsgpt_sandbox" 13 | SANDBOX_IMAGE_NAME = "devopsgpt:py39" 14 | SANDBOX_HOST = os.environ.get("SANDBOX_HOST") or DEFAULT_BIND_HOST # "172.25.0.3" 15 | SANDBOX_SERVER = { 16 | "host": f"http://{SANDBOX_HOST}", 17 | "port": 5050, 18 | "docker_port": 5050, 19 | "url": f"http://{SANDBOX_HOST}:5050", 20 | "do_remote": True, 21 | } 22 | 23 | from start import check_docker, check_process 24 | 25 | try: 26 | client = docker.from_env() 27 | except: 28 | client = None 29 | 30 | 31 | def stop_main(): 32 | # 33 | check_docker(client, SANDBOX_CONTRAINER_NAME, do_stop=True, ) 34 | # 35 | check_docker(client, CONTRAINER_NAME, do_stop=True, ) 36 | 37 | 38 | if __name__ == "__main__": 39 | stop_main() -------------------------------------------------------------------------------- /frontend/.eslintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: require.resolve('@umijs/max/eslint'), 3 | }; 4 | -------------------------------------------------------------------------------- /frontend/.prettierignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | .umi 3 | .umi-production 4 | -------------------------------------------------------------------------------- /frontend/.prettierrc: -------------------------------------------------------------------------------- 1 | { 2 | "printWidth": 80, 3 | "singleQuote": true, 4 | "trailingComma": "all", 5 | "proseWrap": "never", 6 | "overrides": [{ "files": ".prettierrc", "options": { "parser": "json" } }], 7 | "plugins": ["prettier-plugin-organize-imports", "prettier-plugin-packagejson"] 8 | } 9 | -------------------------------------------------------------------------------- /frontend/.stylelintrc.js: -------------------------------------------------------------------------------- 1 | module.exports = { 2 | extends: require.resolve('@umijs/max/stylelint'), 3 | }; 4 | -------------------------------------------------------------------------------- /frontend/.umirc.ts: -------------------------------------------------------------------------------- 1 | import { defineConfig } from '@umijs/max'; 2 | const mockSpaceId = 1; 3 | 4 | export default defineConfig({ 5 | styledComponents: {}, 6 | valtio: {}, 7 | access: {}, 8 | model: {}, 9 | initialState: {}, 10 | request: {}, 11 | layout: false, 12 | locale: { 13 | default: 'zh-CN', 14 | antd: true, 15 | }, 16 | // proxy: { 17 | // '/api': { 18 | // // target: 'https://nexa-api-pre.alipay.com', 19 | // // target: 'http://30.230.0.179:8080', 20 | // target: 'http://runtime:8080', 21 | // // target: 'http://30.98.121.212:8083', 22 | // changeOrigin: true, 23 | // }, 24 | // }, 25 | routes: [ 26 | { 27 | path: '/', 28 | redirect: '/space/default/ekg/default', 29 | }, 30 | { 31 | path: `/space/:spaceId/ekg/:ekgId`, 32 | component: './EKG/Common', 33 | routes: [ 34 | { 35 | path: '', 36 | component: './EKG/index', 37 | }, 38 | { 39 | path: 'flow/:flowId', 40 | component: './EKG/Flow/index', 41 | }, 42 | ], 43 | }, 44 | ], 45 | npmClient: 'pnpm', 46 | }); 47 | -------------------------------------------------------------------------------- /frontend/README.md: -------------------------------------------------------------------------------- 1 | # README 2 | 本项目是`@umijs/max` 模板项目,更多功能参考 [Umi Max 简介](https://umijs.org/docs/max/introduce) 3 | 4 | # 安装依赖 5 | `pnpm i` 6 | 7 | # 启动项目 8 | `pnpm dev` 9 | 10 | # 打开页面 11 | 前端服务运行在`http://localhost:8000/` 12 | 13 | 14 | 15 | -------------------------------------------------------------------------------- /frontend/package.json: -------------------------------------------------------------------------------- 1 | { 2 | "private": true, 3 | "author": "will.jc ", 4 | "scripts": { 5 | "build": "max build", 6 | "dev": "max dev", 7 | "format": "prettier --cache --write .", 8 | "postinstall": "max setup", 9 | "setup": "max setup", 10 | "start": "npm run dev" 11 | }, 12 | "dependencies": { 13 | "@ant-design/icons": "^5.0.1", 14 | "@ant-design/pro-components": "^2.4.4", 15 | "@microsoft/fetch-event-source": "^2.0.1", 16 | "@umijs/max": "^4.3.20", 17 | "antd": "^5.20.6", 18 | "d3-force": "^3.0.0", 19 | "dagre": "^0.8.5", 20 | "fetch-event-source": "^1.0.0-alpha.2", 21 | "highlight.js": "^10.5.0", 22 | "js-cookie": "^3.0.5", 23 | "lodash": "^4.17.21", 24 | "markdown-it": "^14.1.0", 25 | "nanoid": "^5.0.7", 26 | "react-json-editor-ajrm": "^2.5.14", 27 | "react-markdown": "^9.0.1", 28 | "reactflow": "^11.11.3" 29 | }, 30 | "devDependencies": { 31 | "@types/js-cookie": "^3.0.6", 32 | "@types/lodash": "^4.17.9", 33 | "@types/react": "^18.0.33", 34 | "@types/react-dom": "^18.0.11", 35 | "prettier": "^2.8.7", 36 | "prettier-plugin-organize-imports": "^3.2.2", 37 | "prettier-plugin-packagejson": "^2.4.3", 38 | "typescript": "^5.0.3" 39 | }, 40 | "repository": "git@code.alipay.com:codefuse_opensource/muagent.git" 41 | } 42 | -------------------------------------------------------------------------------- /frontend/src/app.ts: -------------------------------------------------------------------------------- 1 | import { createGlobalStyle } from '@umijs/max'; 2 | import type { RequestConfig } from '@umijs/max'; 3 | 4 | // ps: 推master要改成localhost 5 | const API_PREFIX = 'http://localhost:8080'; 6 | // const API_PREFIX = 'http://30.183.176.221:8080'; 7 | 8 | export const request: RequestConfig = { 9 | requestInterceptors: [ 10 | (url, options) => ({ url: `${API_PREFIX}${url}`, options }) 11 | ] 12 | 13 | } 14 | // 全局初始化数据配置,用于 Layout 用户信息和权限初始化 15 | // 更多信息见文档:https://umijs.org/docs/api/runtime-config#getinitialstate 16 | // export async function getInitialState(): Promise<{ name: string }> { 17 | // return { name: '@umijs/max' }; 18 | // } 19 | 20 | export const styledComponents = { 21 | GlobalStyle: createGlobalStyle` 22 | html, 23 | body { 24 | height: 100%; 25 | background-color: #eceff6; 26 | margin: 0; 27 | } 28 | * { 29 | box-sizing: border-box; 30 | } 31 | `, 32 | }; 33 | -------------------------------------------------------------------------------- /frontend/src/assets/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/frontend/src/assets/.gitkeep -------------------------------------------------------------------------------- /frontend/src/components/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/frontend/src/components/.gitkeep -------------------------------------------------------------------------------- /frontend/src/constants/index.tsx: -------------------------------------------------------------------------------- 1 | export const BACKEND_URL = 'http://nexa-114-gz00b.cloudide.dev.alipay.net'; -------------------------------------------------------------------------------- /frontend/src/pages/EKG/Common/Chat/AgentPrologue/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Avatar, Tooltip } from 'antd'; 3 | import { AgentPrologueWrapper } from './style'; 4 | 5 | const AgentPrologue = ({ agent }: any) => { 6 | return ( 7 | 8 |
17 | 25 |

26 | {agent.agentConfig?.name || agent?.agentName} 27 |

28 |
29 | {agent?.agentDesc} 30 |
31 |
32 |
33 | ); 34 | }; 35 | 36 | export default AgentPrologue; 37 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/Common/Chat/AgentPrologue/style.ts: -------------------------------------------------------------------------------- 1 | import { styled } from '@umijs/max'; 2 | 3 | export const AgentPrologueWrapper = styled.div` 4 | width: 100%; 5 | height: 100%; 6 | text-align: center; 7 | display: flex; 8 | justify-content: center; 9 | align-items: center; 10 | .agent_dec { 11 | width: 100%; 12 | display: -webkit-box; 13 | -webkit-box-orient: vertical; 14 | overflow: hidden; 15 | text-overflow: ellipsis; 16 | -webkit-line-clamp: 2; 17 | font-size: 14px; 18 | padding: 0 12px; 19 | } 20 | .agent_questionSample { 21 | width: 100%; 22 | height: auto; 23 | padding: 14px 24px; 24 | margin: 14px 0; 25 | background: #fff; 26 | border-radius: 16px; 27 | -webkit-box-orient: vertical; 28 | overflow: hidden; 29 | text-overflow: ellipsis; 30 | -webkit-line-clamp: 1; 31 | display: flex; 32 | justify-content: space-between; 33 | align-items: center; 34 | } 35 | `; 36 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/Common/Chat/TemplateCode/index copy.tsx: -------------------------------------------------------------------------------- 1 | import hljs from 'highlight.js'; 2 | import 'highlight.js/styles/atom-one-dark.css'; 3 | import 'highlight.js/styles/github.css'; 4 | import MarkdownIt from 'markdown-it'; 5 | import React from 'react'; 6 | import { CodeWrapper } from './style'; 7 | 8 | type TemplateIprops = { 9 | dataSource: string; 10 | }; 11 | 12 | const TemplateCode = ({ dataSource }: TemplateIprops) => { 13 | const md: any = new MarkdownIt({ 14 | html: true, 15 | linkify: true, 16 | typographer: true, 17 | breaks: true, 18 | xhtmlOut: true, 19 | highlight: (str: any, lang: any) => { 20 | if (lang && hljs.getLanguage(lang)) { 21 | try { 22 | // 移除了添加行号的部分,直接返回hljs高亮的结果 23 | const highlightedCode = hljs.highlight(lang, str).value; 24 | return `
${highlightedCode}
`; 25 | } catch (error) { 26 | console.error(error); 27 | } 28 | } 29 | // 如果没有识别到语言,则按原样返回 30 | return `
${md.utils.escapeHtml(str)}
`; 31 | }, 32 | }); 33 | 34 | md.renderer.rules.link_open = (tokens, idx, options, env, self) => { 35 | const token = tokens[idx]; 36 | token.attrPush(['target', '_blank']); 37 | return self.renderToken(tokens, idx, options); 38 | }; 39 | 40 | return ( 41 | 42 |
49 | 50 | ); 51 | }; 52 | 53 | export default TemplateCode; 54 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/Common/Chat/TemplateCode/style.ts: -------------------------------------------------------------------------------- 1 | import { styled } from '@umijs/max'; 2 | 3 | export const CodeWrapper = styled.div` 4 | .code_less p:last-child { 5 | margin-bottom: 0; 6 | } 7 | .hljs { 8 | margin-bottom: 0; 9 | } 10 | .code_less { 11 | padding: 6px; 12 | display: block !important; 13 | } 14 | .hljs { 15 | border-radius: 6px; 16 | } 17 | .code_less { 18 | thead { 19 | background-color: rgb(244, 245, 245); 20 | } 21 | td, 22 | th { 23 | border: 1px solid rgb(231, 233, 232); 24 | padding: 8px; 25 | } 26 | p:first-child { 27 | margin-top: 0; 28 | } 29 | p:last-child { 30 | margin-bottom: 0; 31 | } 32 | } 33 | 34 | .templateCodeCustom { 35 | .ant-collapse { 36 | border-radius: 6px; 37 | } 38 | .ant-collapse-header { 39 | padding: 6px 8px !important; 40 | } 41 | .ant-collapse-content-box { 42 | padding: 0 !important; 43 | } 44 | } 45 | `; 46 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/Common/Chat/index.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import ChatContent from './ChatContent'; 3 | import ChatFooter from './ChatFooter'; 4 | import { ChatContentWrapper } from './style'; 5 | 6 | const Chat = () => { 7 | return ( 8 | 9 | 10 | 11 | 12 | ); 13 | }; 14 | 15 | export default Chat; 16 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/Common/ChatDetail/style.ts: -------------------------------------------------------------------------------- 1 | import { styled } from '@umijs/max'; 2 | 3 | export const ChatDetailWrapper = styled.div` 4 | width: 100%; 5 | height: calc(100% - 65px); 6 | .detailListWrapper { 7 | height: 100%; 8 | overflow: auto; 9 | } 10 | .detailCol { 11 | width: 100%; 12 | padding: 4px 12px; 13 | cursor: pointer; 14 | .dec { 15 | flex: 1; 16 | overflow: hidden; 17 | white-space: nowrap; 18 | text-overflow: ellipsis; 19 | } 20 | } 21 | .detailResultWrapper { 22 | padding: 12px; 23 | .startNodeIcon { 24 | width: 24px; 25 | height: 24px; 26 | border-radius: 50%; 27 | background-image: linear-gradient(180deg, #ffbf1a 0%, #ff8216 100%); 28 | } 29 | .opsgptkgIntentIcon { 30 | width: 24px; 31 | height: 24px; 32 | border-radius: 50%; 33 | background: #5272e0; 34 | } 35 | .opsgptkgScheduleIcon { 36 | width: 24px; 37 | height: 24px; 38 | border-radius: 50%; 39 | background: #5dbb30; 40 | } 41 | } 42 | `; 43 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/Flow/components/ExecutionConditions/style.ts: -------------------------------------------------------------------------------- 1 | import { styled } from '@umijs/max'; 2 | 3 | /** 4 | * 条件执行 5 | */ 6 | export const ExecutionConditionsWrapper = styled.div` 7 | .ant-collapse { 8 | background: #ffffff; 9 | .ant-collapse-item { 10 | background: #000a1a0a; 11 | border-radius: 8px; 12 | border: none; 13 | margin-top: 12px; 14 | } 15 | .ant-collapse-content { 16 | border-top: 1px solid #000a1a1a; 17 | padding-top: 8px; 18 | margin: 0 12px; 19 | } 20 | .ant-collapse-content-box { 21 | padding: 12px 0; 22 | } 23 | .ant-form-item { 24 | margin-bottom: 0; 25 | } 26 | .ant-radio-group { 27 | width: 100%; 28 | } 29 | .conditions-radio { 30 | .conditions-radio-item { 31 | height: 40px; 32 | background: #ffffff; 33 | border-radius: 8px; 34 | padding: 10px 12px; 35 | } 36 | } 37 | } 38 | `; 39 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/Flow/nodes/StartNode.tsx: -------------------------------------------------------------------------------- 1 | import React from 'react'; 2 | import { Handle, Position } from 'reactflow'; 3 | import NodeHeader from '../components/NodeHeader'; 4 | import { NodeContainer } from './style'; 5 | export default (props: any) => { 6 | console.log(props, 'props'); 7 | return ( 8 | 9 | 10 | 20 |
29 |
30 | 34 |
35 |
{props.data.attributes.name}
36 |
37 |
38 | ); 39 | }; 40 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/Flow/nodes/style.ts: -------------------------------------------------------------------------------- 1 | import { styled } from '@umijs/max'; 2 | export const NodeContainer = styled.div` 3 | padding: 12px; 4 | width: 420px; 5 | min-height: 166px; 6 | background: #ffffff; 7 | border-radius: 12px; 8 | box-shadow: 0px 3px 6px -4px #0000001f; 9 | .ant-collapse-header { 10 | padding: 12px !important ; 11 | margin-bottom: 10px; 12 | } 13 | .ant-collapse-content { 14 | min-height: 120px; 15 | } 16 | .summarize-switch { 17 | display: flex; 18 | padding: 0 12px; 19 | margin: 12px 0; 20 | align-items: center; 21 | justify-content: space-between; 22 | background: #000a1a0a; 23 | border-radius: 8px; 24 | width: 100%; 25 | height: 40px; 26 | font-size: 14px; 27 | color: #1c2533; 28 | font-weight: 600; 29 | } 30 | `; 31 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/Flow/store/index.tsx: -------------------------------------------------------------------------------- 1 | import { proxy } from '@umijs/max'; 2 | 3 | const EKGChildFlowState = proxy({ 4 | /** 5 | * 当前画布数据 6 | */ 7 | currentGraphData: { 8 | nodes: [], 9 | edges: [], 10 | nodeHeaderStatus: false, 11 | nodeHeaderStatusInfo: {}, 12 | }, 13 | } as { 14 | currentGraphData: { 15 | nodes: any[]; 16 | edges: any[]; 17 | nodeHeaderStatus?: boolean; 18 | nodeHeaderStatusInfo?: { [key: string]: any }; 19 | }; 20 | }); 21 | 22 | export { EKGChildFlowState }; 23 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/Flow/style.ts: -------------------------------------------------------------------------------- 1 | import { styled } from '@umijs/max'; 2 | 3 | export const ChildrenFlowContainer = styled.div` 4 | .react-flow__attribution { 5 | display: none; 6 | } 7 | height: 100vh; 8 | width: 100vw; 9 | `; 10 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/Flow/utils/ChildNodeTemplate.ts: -------------------------------------------------------------------------------- 1 | // export const startNode = { 2 | // logo: 'https://mdn.alipayobjects.com/huamei_5qayww/afts/img/A*onSLQLtYSzkAAAAAAAAAAAAADprcAQ/original', 3 | // name: '开始', 4 | // type: 'startNode', 5 | // }; 6 | export const taskNode = { 7 | logo: 'https://mdn.alipayobjects.com/huamei_5qayww/afts/img/A*yAbSSbagshMAAAAAAAAAAAAADprcAQ/original', 8 | name: '任务执行', 9 | type: 'opsgptkg_task', 10 | isVerification: false, 11 | attributes: { 12 | executetype: 'onlyTool', 13 | accesscriteria: '', 14 | description: '', 15 | }, 16 | }; 17 | export const chooseNode = { 18 | logo: 'https://mdn.alipayobjects.com/huamei_5qayww/afts/img/A*kq5pRbKCVdEAAAAAAAAAAAAADprcAQ/original', 19 | name: '条件分支', 20 | type: 'opsgptkg_phenomenon', 21 | isVerification: false, 22 | attributes: { 23 | description: '', 24 | }, 25 | }; 26 | export const endNode = { 27 | logo: 'https://mdn.alipayobjects.com/huamei_5qayww/afts/img/A*5reDQ6Z-3vIAAAAAAAAAAAAADprcAQ/original', 28 | name: '结论', 29 | type: 'opsgptkg_analysis', 30 | isVerification: false, 31 | attributes: { 32 | dsltemplate: '', 33 | summaryswitch: false, 34 | accesscriteria: '', 35 | description: '', 36 | }, 37 | }; 38 | export const ChildNodeTemplate = { 39 | label: '内容生成', 40 | list: [taskNode, chooseNode, endNode], 41 | }; 42 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/Flow/utils/random.tsx: -------------------------------------------------------------------------------- 1 | import { customAlphabet } from 'nanoid'; 2 | 3 | export function createWorkflowRandom() { 4 | return customAlphabet( 5 | 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789', 6 | 32, 7 | )(); //随机生成节点id 8 | } 9 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/Flow/utils/typeFlow.tsx: -------------------------------------------------------------------------------- 1 | export type FlowModuleTemplateType = { 2 | type: string; 3 | name: string; 4 | }; 5 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/NodeTemplate.ts: -------------------------------------------------------------------------------- 1 | /** 2 | * 知识图谱-开始节点 3 | */ 4 | export const startNode = { 5 | name: '开始', 6 | type: 'startNode', 7 | }; 8 | 9 | /** 10 | * 知识图谱-场景意图节点 11 | */ 12 | export const sceneNode = { 13 | name: '场景意图', 14 | label: '场景意图', 15 | type: 'opsgptkg_intent', 16 | attributes: { 17 | name: '场景意图', 18 | description: '', 19 | }, 20 | }; 21 | 22 | /** 23 | * 知识图谱-操作计划节点 24 | */ 25 | export const operationPlanNode = { 26 | name: '操作计划', 27 | type: 'opsgptkg_schedule', 28 | attributes: { 29 | name: '操作计划', 30 | description: '操作计划', 31 | enable: true, 32 | }, 33 | }; 34 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/components/EKGHeader/style.ts: -------------------------------------------------------------------------------- 1 | import { styled } from '@umijs/max'; 2 | /** 3 | * 编排头部 4 | */ 5 | export const EKGHeaderWrapper = styled.div` 6 | height: 56px; 7 | padding: 0 16px; 8 | background: #f5f7fa; 9 | border: 1px solid #ffffffcd; 10 | border-radius: 12px; 11 | user-select: none; 12 | .header-title { 13 | font-size: 16px; 14 | color: #1c2533; 15 | font-weight: 600; 16 | } 17 | .header-save-tip { 18 | font-size: 12px; 19 | color: #000a1a78; 20 | } 21 | .header-tab { 22 | font-size: 20px; 23 | color: #525964; 24 | cursor: pointer; 25 | } 26 | .header-active-tab { 27 | color: #1b62ff; 28 | font-weight: 600; 29 | } 30 | .header-children-wrapper { 31 | width: 320px; 32 | background-color: #fff; 33 | padding: 4px 12px; 34 | border-radius: 10px; 35 | .header-children-name { 36 | font-size: 16px; 37 | color: #000a1ae3; 38 | font-weight: 600; 39 | margin: 0 8px; 40 | } 41 | } 42 | `; 43 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/components/EditKnowledgeModal/style.ts: -------------------------------------------------------------------------------- 1 | import { styled } from '@umijs/max'; 2 | import { Modal } from 'antd'; 3 | 4 | // 创建知识弹窗 5 | export const EditKnowledgeModalWrapper = styled(Modal)` 6 | textarea { 7 | height: 113px; 8 | resize: none; 9 | } 10 | .ant-modal-content, 11 | .ant-modal-title { 12 | background: #eceff6; 13 | } 14 | .mode-item { 15 | border-radius: 12px; 16 | padding: 12px; 17 | margin-bottom: 16px; 18 | cursor: pointer; 19 | .ant-card-body { 20 | padding: 0; 21 | } 22 | .mode-item-title { 23 | font-size: 14px; 24 | color: #1c2533; 25 | font-weight: 600; 26 | } 27 | .mode-item-description { 28 | margin-top: 8px; 29 | font-size: 14px; 30 | color: #878c93; 31 | line-height: 24px; 32 | } 33 | } 34 | .mode-item-active { 35 | border: 1.6px solid #1b62ff; 36 | } 37 | `; 38 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/components/SearchNode/index.tsx: -------------------------------------------------------------------------------- 1 | import { searchNode as queryNode } from '@/services/nexa/EkgProdController'; 2 | import { SearchOutlined } from '@ant-design/icons'; 3 | import { useParams, useRequest } from '@umijs/max'; 4 | import { Input, message, Spin } from 'antd'; 5 | import React from 'react'; 6 | import { EKGFlowState } from '../../store'; 7 | 8 | const SearchNode = () => { 9 | const { spaceId } = useParams(); 10 | 11 | /** 12 | * 搜索节点 13 | */ 14 | const queryNodeInfo = useRequest(queryNode, { 15 | manual: true, 16 | formatResult: (res) => res, 17 | onSuccess: (res) => { 18 | if (res?.success) { 19 | EKGFlowState.nodeActionList = { 20 | type: 'search', 21 | data: { 22 | nodes: res?.data || [], 23 | }, 24 | }; 25 | } else { 26 | message.error(res?.errorMessage); 27 | } 28 | }, 29 | }); 30 | 31 | return ( 32 | 33 | } 38 | style={{ width: '320px' }} 39 | onPressEnter={(e: React.KeyboardEvent) => { 40 | queryNodeInfo.run({ 41 | teamId: spaceId, 42 | text: (e.target as HTMLInputElement).value, 43 | }); 44 | }} 45 | onChange={(e) => { 46 | if (e.target.value === '') { 47 | EKGFlowState.nodeActionList = { 48 | type: '', 49 | data: {}, 50 | }; 51 | } 52 | }} 53 | /> 54 | 55 | ); 56 | }; 57 | 58 | export default SearchNode; 59 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/flow.d.ts: -------------------------------------------------------------------------------- 1 | import type { XYPosition } from 'reactflow'; 2 | 3 | export type ITemplate = { 4 | type: string; 5 | name: string; 6 | attributes?: any; 7 | }; 8 | 9 | export type IConnectParam = { 10 | /** 11 | * 节点id 12 | */ 13 | nodeId: string; 14 | /** 15 | * 来源桩点的索引 16 | */ 17 | sourceHandleIndex: number; 18 | /** 19 | * 节点类型 20 | */ 21 | type?: string; 22 | position: XYPosition; 23 | }; 24 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/nodes/StartNode/style.ts: -------------------------------------------------------------------------------- 1 | import { styled } from '@umijs/max'; 2 | 3 | export const StartNodeWrapper = styled.div` 4 | .node-circle { 5 | width: 64px; 6 | height: 64px; 7 | border-radius: 50%; 8 | background-image: linear-gradient(180deg, #ffbf1a 0%, #ff8216 100%); 9 | font-size: 16px; 10 | color: #ffffff; 11 | position: relative; 12 | .node-circle-label { 13 | font-weight: 600; 14 | } 15 | .node-circle-handle-dot { 16 | width: 4px; 17 | height: 4px; 18 | background: #fff; 19 | border: 1px solid #1b62ff; 20 | left: 50%; 21 | top: 50%; 22 | } 23 | .node-circle-handle-dot:hover { 24 | width: 16px; 25 | height: 16px; 26 | background-image: url('https://mdn.alipayobjects.com/huamei_5qayww/afts/img/A*HjOMRJveUSAAAAAAAAAAAAAADprcAQ/original'); 27 | background-position: center; 28 | } 29 | } 30 | .node-title { 31 | width: 120px; 32 | position: absolute; 33 | top: 68px; 34 | font-size: 12px; 35 | color: #000a1ae3; 36 | text-align: center; 37 | } 38 | .ant-menu { 39 | font-size: 14px; 40 | border-radius: 12px; 41 | padding: 4px; 42 | .ant-menu-item { 43 | height: 36px; 44 | text-align: center; 45 | padding: 0 4px; 46 | color: #000000e0; 47 | font-weight: 400; 48 | } 49 | } 50 | `; 51 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/service/index.ts: -------------------------------------------------------------------------------- 1 | import { request } from '@umijs/max'; 2 | export async function getSreAgentFlow(sessionId: string) { 3 | return request('/sreAgent/v1/opsconvobus/ekgGraph/query', { 4 | method: 'POST', 5 | headers: { 6 | 'Content-Type': 'application/json', 7 | }, 8 | data: { 9 | sessionId, 10 | }, 11 | }); 12 | } 13 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/store/index.tsx: -------------------------------------------------------------------------------- 1 | import { proxy } from '@umijs/max'; 2 | 3 | type NodeDetailProps = { 4 | type?: 'startNode' | 'operationPlanNode'; 5 | title?: string; 6 | description?: string; 7 | [key: string]: any; 8 | enable?: boolean; 9 | }; 10 | 11 | type GNodeData = { 12 | nodes: NEXA_API.GNode[]; 13 | }; 14 | 15 | interface NodeActionListProps { 16 | type: 'search' | 'select' | ''; 17 | data: GNodeData | NEXA_API.GGraph; 18 | } 19 | 20 | interface EKGFlowStateProps { 21 | currentGraphData: { 22 | nodes: any[]; 23 | edges: any[]; 24 | }; 25 | oldGraphData: { 26 | nodes: any[]; 27 | edges: any[]; 28 | }; 29 | connectStartParams?: { 30 | handleId: string; 31 | handleType: string; 32 | nodeId: string; 33 | }; 34 | nodeDetailOpen: boolean; 35 | nodeDetailData: NodeDetailProps; 36 | knowledgeData: NEXA_API.NexaKnowledgeBaseVO; 37 | nodeActionList: NodeActionListProps; 38 | } 39 | 40 | const EKGFlowState = proxy({ 41 | /** 42 | * 当前画布数据 43 | */ 44 | currentGraphData: { 45 | nodes: [], 46 | edges: [], 47 | }, 48 | oldGraphData: { 49 | nodes: [], 50 | edges: [], 51 | }, 52 | /** 53 | * 开始进行连接时,桩点的数据 54 | */ 55 | connectStartParams: { 56 | handleId: '', 57 | handleType: '', 58 | nodeId: '', 59 | }, 60 | /** 61 | * 节点操作面板显隐 62 | */ 63 | nodeDetailOpen: false, 64 | /** 65 | * 节点操作面板数据 66 | */ 67 | nodeDetailData: {}, 68 | /** 69 | * 知识库名称、描述等信息 70 | */ 71 | knowledgeData: {}, 72 | /** 73 | * 搜索节点数据 74 | */ 75 | nodeActionList: { type: '', data: {} }, 76 | } as EKGFlowStateProps); 77 | 78 | export { EKGFlowState, EKGFlowStateProps }; 79 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/style.ts: -------------------------------------------------------------------------------- 1 | import { styled } from '@umijs/max'; 2 | 3 | export const EKGFlowContainer = styled.div` 4 | height: 100vh; 5 | width: 100vw; 6 | .react-flow__attribution { 7 | display: none; 8 | } 9 | .custom-controls { 10 | position: absolute; 11 | right: 16px !important; 12 | bottom: 16px !important; 13 | height: 40px !important; 14 | pointer-events: auto; 15 | margin: 0; 16 | padding: 0; 17 | box-shadow: none; 18 | } 19 | 20 | .zoom-containers { 21 | background: #ffffff; 22 | border-radius: 12px; 23 | height: 40px; 24 | width: 173px; 25 | display: flex; 26 | align-items: center; 27 | } 28 | 29 | .dividing-line { 30 | width: 1px; 31 | height: 24px; 32 | background: #000a1a1a; 33 | } 34 | 35 | .no-border { 36 | border-width: 0px; 37 | .ant-btn-icon { 38 | width: 16px; 39 | height: 16px; 40 | } 41 | } 42 | .doc-analysis { 43 | width: 40px; 44 | height: 40px; 45 | display: flex; 46 | justify-content: center; 47 | align-items: center; 48 | border-radius: 50%; 49 | background: #1c2533; 50 | cursor: pointer; 51 | } 52 | `; 53 | 54 | /** 55 | * 解析文件内容 56 | */ 57 | export const DocAnalysisWrapper = styled.div` 58 | width: 344px; 59 | overflow-y: auto; 60 | overflow-x: hidden; 61 | max-height: 186px; 62 | transition: max-height 0.3s; 63 | padding: 0 8px; 64 | margin: 0 4px; 65 | `; 66 | -------------------------------------------------------------------------------- /frontend/src/pages/EKG/utils/nodeAction.ts: -------------------------------------------------------------------------------- 1 | import { EKGFlowState } from '@/pages/EKG/store'; 2 | import { getNodeAncestor } from '@/services/nexa/EkgProdController'; 3 | import { useRequest } from '@umijs/max'; 4 | import { useEffect } from 'react'; 5 | 6 | interface AncestorParams { 7 | teamId: string; 8 | nodeId: string; 9 | nodeType: 'opsgptkg_intent' | 'opsgptkg_schedule'; 10 | } 11 | 12 | export const useSearchAncestor = ( 13 | params: AncestorParams, 14 | callback?: (res: any) => void, 15 | ) => { 16 | const { run, data, error, loading, cancel } = useRequest(getNodeAncestor, { 17 | manual: true, 18 | }); 19 | 20 | const searchAncestor = () => { 21 | run(params); 22 | }; 23 | 24 | useEffect(() => { 25 | if (data) { 26 | if (callback) { 27 | callback(data); 28 | } 29 | console.log('data<<', data); 30 | EKGFlowState.nodeActionList = { 31 | type: 'select', 32 | data, 33 | }; 34 | } 35 | }, [data, callback]); 36 | 37 | useEffect(() => { 38 | if (error) { 39 | console.error('节点搜索出错:', error); 40 | } 41 | }, [error]); 42 | 43 | useEffect(() => { 44 | cancel(); 45 | }, []); 46 | 47 | return { searchAncestor, loading, data }; 48 | }; 49 | -------------------------------------------------------------------------------- /frontend/src/services/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/frontend/src/services/.gitkeep -------------------------------------------------------------------------------- /frontend/src/services/afs2demo/opsconvobus/EkgGraphController.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | import { request } from '@umijs/max'; 3 | 4 | /** 展示EKG运行时的树形(意图+操作计划)节点 5 | @param conversationId 6 | @return 7 | GET /v1/opsconvobus/ekgGraph/intentTree */ 8 | export async function intent( 9 | params: { 10 | // query 11 | conversationId?: string; 12 | }, 13 | options?: { [key: string]: any }, 14 | ) { 15 | return request>('/v1/opsconvobus/ekgGraph/intentTree', { 16 | method: 'GET', 17 | params: { 18 | ...params, 19 | }, 20 | // @ts-ignore 21 | appName: 'opsconvobus', 22 | ...(options || {}), 23 | }); 24 | } 25 | 26 | /** POST /v1/opsconvobus/ekgGraph/query */ 27 | export async function query(body?: any, options?: { [key: string]: any }) { 28 | return request>('/v1/opsconvobus/ekgGraph/query', { 29 | method: 'POST', 30 | headers: { 31 | 'Content-Type': 'application/json', 32 | }, 33 | data: body, 34 | // @ts-ignore 35 | appName: 'opsconvobus', 36 | ...(options || {}), 37 | }); 38 | } 39 | -------------------------------------------------------------------------------- /frontend/src/services/afs2demo/opsconvobus/index.ts: -------------------------------------------------------------------------------- 1 | /* eslint-disable */ 2 | import * as EkgGraphController from './EkgGraphController'; 3 | 4 | export default { 5 | EkgGraphController, 6 | }; 7 | -------------------------------------------------------------------------------- /frontend/src/services/user.ts: -------------------------------------------------------------------------------- 1 | import { request } from '@umijs/max'; 2 | 3 | // 获取用户个人信息 4 | export async function getUserInfo() { 5 | return request('/user/getCurrentUser.json', { 6 | method: 'POST', 7 | headers: { 8 | 'Content-Type': 'application/json', 9 | }, 10 | }); 11 | } 12 | -------------------------------------------------------------------------------- /frontend/src/utils/.gitkeep: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/frontend/src/utils/.gitkeep -------------------------------------------------------------------------------- /frontend/tsconfig.json: -------------------------------------------------------------------------------- 1 | { 2 | "extends": "./src/.umi/tsconfig.json" 3 | } 4 | -------------------------------------------------------------------------------- /frontend/typings.d.ts: -------------------------------------------------------------------------------- 1 | import '@umijs/max/typings'; 2 | -------------------------------------------------------------------------------- /muagent/__init__.py: -------------------------------------------------------------------------------- 1 | from .ekg_project import EKG, get_ekg_project_config_from_env 2 | from .project_manager import get_project_config_from_env 3 | from .models import get_model 4 | from .agents import get_agent 5 | from .tools import get_tool 6 | 7 | __all__ = [ 8 | "EKG", "get_model", "get_agent", "get_tool", 9 | "get_ekg_project_config_from_env", 10 | "get_project_config_from_env" 11 | ] -------------------------------------------------------------------------------- /muagent/agents/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_agent import BaseAgent 2 | from .single_agent import SingleAgent 3 | from .react_agent import ReactAgent 4 | from .task_agent import TaskAgent 5 | from .group_agent import GroupAgent 6 | from .user_agent import UserAgent 7 | from .functioncall_agent import FunctioncallAgent 8 | from ..schemas import AgentConfig 9 | 10 | __all__ = [ 11 | "BaseAgent", 12 | "SingleAgent", 13 | "ReactAgent", 14 | "TaskAgent", 15 | "GroupAgent", 16 | "UserAgent", 17 | "FunctioncallAgent" 18 | ] 19 | 20 | 21 | def get_agent(agent_config: AgentConfig) -> BaseAgent: 22 | """Get the agent by agent config 23 | 24 | Args: 25 | agent_config (`AgentConfig`): The agent config 26 | 27 | Returns: 28 | `BaseAgent`: The specific agent 29 | """ 30 | return BaseAgent.init_from_project_config(agent_config) -------------------------------------------------------------------------------- /muagent/agents/util.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/agents/util.py -------------------------------------------------------------------------------- /muagent/base_configs/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/base_configs/__init__.py -------------------------------------------------------------------------------- /muagent/base_configs/extra_keywords.txt: -------------------------------------------------------------------------------- 1 | 花呗 2 | 借呗 3 | 余额宝 -------------------------------------------------------------------------------- /muagent/base_configs/prompts/agent_selector_template_prompt.py: -------------------------------------------------------------------------------- 1 | SELECTOR_AGENT_TEMPLATE_PROMPT = """#### Agent Profile 2 | 3 | Your goal is to response according the Context Data's information with the role that will best facilitate a solution, taking into account all relevant context (Context) provided. 4 | 5 | When you need to select the appropriate role for handling a user's query, carefully read the provided role names, role descriptions and tool list. 6 | 7 | ATTENTION: response carefully referenced "Response Output Format" in format. 8 | 9 | #### Response Output Format 10 | 11 | **Thoughts:** think the reason step by step about why you selecte one role 12 | 13 | **Role:** Select the role from agent names. 14 | 15 | """ 16 | 17 | 18 | # #### Input Format 19 | 20 | # **Origin Query:** the initial question or objective that the user wanted to achieve 21 | 22 | # **Context:** the context history to determine if Origin Query has been achieved. -------------------------------------------------------------------------------- /muagent/base_configs/prompts/checker_template_prompt.py: -------------------------------------------------------------------------------- 1 | 2 | CHECKER_TEMPLATE_PROMPT = """#### Agent Profile 3 | 4 | When users have completed a sequence of tasks or if there is clear evidence that no further actions are required, your role is to confirm the completion. 5 | Your task is to assess the current situation based on the context and determine whether all objectives have been met. 6 | Each decision should be justified based on the context provided, specifying if the tasks are indeed finished, or if there is potential for continued activity. 7 | 8 | #### Input Format 9 | 10 | **Origin Query:** the initial question or objective that the user wanted to achieve 11 | 12 | **Context:** the current status and history of the tasks to determine if Origin Query has been achieved. 13 | 14 | #### Response Output Format 15 | **Action Status:** finished or continued 16 | If it's 'finished', the context can answer the origin query. 17 | If it's 'continued', the context cant answer the origin query. 18 | 19 | **REASON:** Justify the decision of choosing 'finished' and 'continued' by evaluating the progress step by step. 20 | Consider all relevant information. If the tasks were aimed at an ongoing process, assess whether it has reached a satisfactory conclusion. 21 | """ 22 | 23 | CHECKER_PROMPT = """尽可能地以有帮助和准确的方式回应人类,判断问题是否得到解答,同时展现解答的过程和内容。 24 | 用户的问题:{query} 25 | 使用 JSON Blob 来指定一个返回的内容,提供一个 action(行动)。 26 | 有效的 'action' 值为:'finished'(任务已经完成,或是需要用户提供额外信息的输入) or 'continue' (历史记录的信息还不足以回答问题)。 27 | 在每个 $JSON_BLOB 中仅提供一个 action,如下所示: 28 | ``` 29 | {{'content': '提取“背景信息”和“对话信息”中信息来回答问题', 'reason': '解释$ACTION的原因', 'action': $ACTION}} 30 | ``` 31 | 按照以下格式进行回应: 32 | 问题:输入问题以回答 33 | 行动: 34 | ``` 35 | $JSON_BLOB 36 | ``` 37 | """ -------------------------------------------------------------------------------- /muagent/base_configs/prompts/functioncall_template_prompt.py: -------------------------------------------------------------------------------- 1 | 2 | FUNCTION_CALL_PROMPT_en = """You have access to the following functions: 3 | 4 | {tool_desc} 5 | 6 | To call a function, please respond with JSON for a function call. 7 | 8 | Respond in the format [{"name": function name, "arguments": dictionary of argument name and its value}]. 9 | """ 10 | 11 | FC_AUTO_PROMPT_en = """ 12 | The function can be called zero or multiple according to your needs. 13 | """ 14 | 15 | 16 | FC_REQUIRED_PROMPT_en = """ 17 | You must call a function as least. 18 | """ 19 | 20 | FC_PARALLEL_PROMPT_en = """ 21 | The function can be called in parallel. 22 | """ 23 | 24 | 25 | FC_RESPONSE_PROMPT_en = """## Response Ouput 26 | Response the function calls by formatting the in JSON. The format should be: 27 | 28 | ```json 29 | [ 30 | { 31 | "name": function name, 32 | "arguments": dictionary of argument name and its value 33 | } 34 | ] 35 | ``` 36 | """ -------------------------------------------------------------------------------- /muagent/base_configs/prompts/input_template_prompt.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | BASE_PROMPT_INPUT = '''#### Begin!!! 4 | ''' 5 | 6 | PLAN_PROMPT_INPUT = '''#### Begin!!! 7 | **Question:** {query} 8 | ''' 9 | 10 | REACT_PROMPT_INPUT = '''#### Begin!!! 11 | {query} 12 | ''' 13 | 14 | 15 | CONTEXT_PROMPT_INPUT = '''#### Begin!!! 16 | **Context:** {context} 17 | ''' 18 | 19 | QUERY_CONTEXT_DOC_PROMPT_INPUT = '''#### Begin!!! 20 | **Origin Query:** {query} 21 | 22 | **Context:** {context} 23 | 24 | **DocInfos:** {DocInfos} 25 | ''' 26 | 27 | QUERY_CONTEXT_PROMPT_INPUT = '''#### Begin!!! 28 | **Origin Query:** {query} 29 | 30 | **Context:** {context} 31 | ''' 32 | 33 | EXECUTOR_PROMPT_INPUT = '''#### Begin!!! 34 | {query} 35 | ''' 36 | 37 | BEGIN_PROMPT_INPUT = '''#### Begin!!! 38 | ''' 39 | 40 | CHECK_PROMPT_INPUT = '''下面是用户的原始问题:{query}''' 41 | -------------------------------------------------------------------------------- /muagent/base_configs/prompts/react_template_prompt.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | REACT_TEMPLATE_PROMPT = """#### Agent Profile 4 | 5 | 1. When users need help with coding, your role is to provide precise and effective guidance. 6 | 2. Reply follows the format of Thoughts/Action Status/Action/Observation cycle. 7 | 3. Provide the final answer if they can solve the problem, otherwise, write the code step by step, showing only the part necessary to solve the current problem. 8 | Each reply should contain only the guidance required for the current step either by tool usage or code. 9 | 4. If the Response already contains content, continue writing following the format of the Response Output Format. 10 | 11 | ATTENTION: Under the "Response" heading, the output format strictly adheres to the content specified in the "Response Output Format." 12 | 13 | #### Response Output Format 14 | 15 | **Question:** First, clarify the problem to be solved. 16 | 17 | **Thoughts:** Based on the Session Records or observations above, provide the plan for executing this step. 18 | 19 | **Action Status:** Set to either 'stopped' or 'code_executing'. If it's 'stopped', the next action is to provide the final answer to the original question. If it's 'code_executing', the next step is to write the code. 20 | 21 | **Action:** Code according to your thoughts. Use this format for code: 22 | 23 | ```python 24 | # Write your code here 25 | ``` 26 | 27 | **Observation:** Check the results and effects of the executed code. 28 | 29 | ... (Repeat this "Thoughts/Action Status/Action/Observation" cycle format as needed) 30 | 31 | **Thoughts:** Considering the session records and executed steps, give the final answer. 32 | 33 | **Action Status:** stopped 34 | 35 | **Action:** Response the final answer to the session records. 36 | 37 | """ -------------------------------------------------------------------------------- /muagent/base_configs/prompts/react_tool_code_planner_prompt.py: -------------------------------------------------------------------------------- 1 | REACT_TOOL_AND_CODE_PLANNER_PROMPT = """#### Agent Profile 2 | When users seek assistance in breaking down complex issues into manageable and actionable steps, 3 | your responsibility is to deliver a well-organized strategy or resolution through the use of tools or coding. 4 | 5 | ATTENTION: response carefully referenced "Response Output Format" in format. 6 | 7 | #### Input Format 8 | 9 | **Question:** First, clarify the problem to be solved. 10 | 11 | #### Response Output Format 12 | 13 | **Action Status:** Set to 'planning' to provide a sequence of tasks, or 'only_answer' to provide a direct response without a plan. 14 | 15 | **Action:** 16 | ```list 17 | "First, we should ...", 18 | ] 19 | ``` 20 | 21 | Or, provide the direct answer. 22 | """ 23 | 24 | # REACT_TOOL_AND_CODE_PLANNER_PROMPT = """你是一个工具和代码使用过程的计划拆解助手,将问题拆解为一系列的工具使用计划,若没有可用工具则使用代码,尽可能地以有帮助和准确的方式回应人类,你可以使用以下工具: 25 | # {formatted_tools} 26 | # 使用 JSON Blob 来指定一个返回的内容,提供一个 action(行动)和一个 plans (生成的计划)。 27 | # 有效的 'action' 值为:'planning'(拆解计划) or 'only_answer' (不需要拆解问题即可直接回答问题)。 28 | # 有效的 'plans' 值为: 一个任务列表,按顺序写出需要使用的工具和使用该工具的理由 29 | # 在每个 $JSON_BLOB 中仅提供一个 action,如下两个示例所示: 30 | # ``` 31 | # {{'action': 'planning', 'plans': [$PLAN1, $PLAN2, $PLAN3, ..., $PLANN], }} 32 | # ``` 33 | # 或者 若无法通过以上工具或者代码解决问题,则直接回答问题 34 | # ``` 35 | # {{'action': 'only_answer', 'plans': "直接回答问题", }} 36 | # ``` 37 | 38 | # 按照以下格式进行回应($JSON_BLOB要求符合上述规定): 39 | # 问题:输入问题以回答 40 | # 行动: 41 | # ``` 42 | # $JSON_BLOB 43 | # ``` 44 | # """ -------------------------------------------------------------------------------- /muagent/base_configs/prompts/refine_template_prompt.py: -------------------------------------------------------------------------------- 1 | REFINE_TEMPLATE_PROMPT = """#### Agent Profile 2 | 3 | When users have a sequence of tasks that require optimization or adjustment based on feedback from the context, your role is to refine the existing plan. 4 | Your task is to identify where improvements can be made and provide a revised plan that is more efficient or effective. 5 | Each instruction should be an enhancement of the existing plan and should specify the step from which the changes should be implemented. 6 | 7 | #### Input Format 8 | 9 | **Context:** Review the history of the plan and feedback to identify areas for improvement. 10 | Take into consideration all feedback information from the current step. If there is no existing plan, generate a new one. 11 | 12 | #### Response Output Format 13 | 14 | **REASON:** think the reason of why choose 'finished', 'unchanged' or 'adjusted' step by step. 15 | 16 | **Action Status:** Set to 'finished', 'unchanged' or 'adjusted'. 17 | If it's 'finished', all tasks are accomplished, and no adjustments are needed, so PLAN_STEP is set to -1. 18 | If it's 'unchanged', this PLAN has no problem, just set PLAN_STEP to CURRENT_STEP+1. 19 | If it's 'adjusted', the PLAN is to provide an optimized version of the original plan. 20 | 21 | **PLAN:** 22 | ```list 23 | [ 24 | "First, we should ...", 25 | ] 26 | ``` 27 | 28 | **PLAN_STEP:** Set to the plan index from which the changes should start. Index range from 0 to n-1 or -1 29 | If it's 'finished', the PLAN_STEP is -1. If it's 'adjusted', the PLAN_STEP is the index of the first revised task in the sequence. 30 | """ -------------------------------------------------------------------------------- /muagent/base_configs/prompts/summary_template_prompt.py: -------------------------------------------------------------------------------- 1 | CONV_SUMMARY_PROMPT = """尽可能地以有帮助和准确的方式回应人类,根据“背景信息”中的有效信息回答问题, 2 | 使用 JSON Blob 来指定一个返回的内容,提供一个 action(行动)。 3 | 有效的 'action' 值为:'finished'(任务已经可以通过上下文信息可以回答) or 'continue' (根据背景信息回答问题)。 4 | 在每个 $JSON_BLOB 中仅提供一个 action,如下所示: 5 | ``` 6 | {{'action': $ACTION, 'content': '根据背景信息回答问题'}} 7 | ``` 8 | 按照以下格式进行回应: 9 | 问题:输入问题以回答 10 | 行动: 11 | ``` 12 | $JSON_BLOB 13 | ``` 14 | """ 15 | 16 | CONV_SUMMARY_PROMPT = """尽可能地以有帮助和准确的方式回应人类 17 | 根据“背景信息”中的有效信息回答问题,同时展现解答的过程和内容 18 | 若能根“背景信息”回答问题,则直接回答 19 | 否则,总结“背景信息”的内容 20 | """ 21 | 22 | 23 | CONV_SUMMARY_PROMPT_SPEC = """ 24 | Your job is to summarize a history of previous messages in a conversation between an AI persona and a human. 25 | The conversation you are given is a fixed context window and may not be complete. 26 | Messages sent by the AI are marked with the 'assistant' role. 27 | The AI 'assistant' can also make calls to functions, whose outputs can be seen in messages with the 'function' role. 28 | Things the AI says in the message content are considered inner monologue and are not seen by the user. 29 | The only AI messages seen by the user are from when the AI uses 'send_message'. 30 | Messages the user sends are in the 'user' role. 31 | The 'user' role is also used for important system events, such as login events and heartbeat events (heartbeats run the AI's program without user action, allowing the AI to act without prompting from the user sending them a message). 32 | Summarize what happened in the conversation from the perspective of the AI (use the first person). 33 | Keep your summary less than 100 words, do NOT exceed this word limit. 34 | Only output the summary, do NOT include anything else in your output. 35 | 36 | --- conversation 37 | {conversation} 38 | --- 39 | 40 | """ -------------------------------------------------------------------------------- /muagent/chat/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_chat import Chat 2 | from .knowledge_chat import KnowledgeChat 3 | from .llm_chat import LLMChat 4 | from .search_chat import SearchChat 5 | from .code_chat import CodeChat 6 | from .agent_chat import AgentChat 7 | 8 | 9 | __all__ = [ 10 | "Chat", "KnowledgeChat", "LLMChat", "SearchChat", "CodeChat", "AgentChat" 11 | ] 12 | -------------------------------------------------------------------------------- /muagent/chat/llm_chat.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from typing import List 3 | 4 | from langchain.chains.llm import LLMChain 5 | from langchain.callbacks import AsyncIteratorCallbackHandler 6 | from langchain.prompts.chat import ChatPromptTemplate 7 | 8 | 9 | from muagent.chat.utils import History, wrap_done 10 | from muagent.llm_models.llm_config import LLMConfig, EmbedConfig 11 | from .base_chat import Chat 12 | from loguru import logger 13 | 14 | 15 | class LLMChat(Chat): 16 | 17 | def __init__( 18 | self, 19 | engine_name: str = "", 20 | top_k: int = 1, 21 | stream: bool = False, 22 | ) -> None: 23 | super().__init__(engine_name, top_k, stream) 24 | 25 | def create_task(self, query: str, history: List[History], model, llm_config: LLMConfig, embed_config: EmbedConfig, **kargs): 26 | '''构建 llm 生成任务''' 27 | chat_prompt = ChatPromptTemplate.from_messages( 28 | [i.to_msg_tuple() for i in history] + [("human", "{input}")] 29 | ) 30 | chain = LLMChain(prompt=chat_prompt, llm=model) 31 | content = chain({"input": query}) 32 | return {"answer": "", "docs": ""}, content 33 | 34 | def create_atask(self, query, history: List[History], model, llm_config: LLMConfig, embed_config: EmbedConfig, callback: AsyncIteratorCallbackHandler): 35 | chat_prompt = ChatPromptTemplate.from_messages( 36 | [i.to_msg_tuple() for i in history] + [("human", "{input}")] 37 | ) 38 | chain = LLMChain(prompt=chat_prompt, llm=model) 39 | task = asyncio.create_task(wrap_done( 40 | chain.acall({"input": query}), callback.done 41 | )) 42 | return task, {"answer": "", "docs": ""} -------------------------------------------------------------------------------- /muagent/chat/utils.py: -------------------------------------------------------------------------------- 1 | import asyncio 2 | from typing import Awaitable 3 | from pydantic import BaseModel, Field 4 | 5 | 6 | async def wrap_done(fn: Awaitable, event: asyncio.Event): 7 | """Wrap an awaitable with a event to signal when it's done or an exception is raised.""" 8 | try: 9 | await fn 10 | except Exception as e: 11 | # TODO: handle exception 12 | print(f"Caught exception: {e}") 13 | finally: 14 | # Signal the aiter to stop. 15 | event.set() 16 | 17 | 18 | class History(BaseModel): 19 | """ 20 | 对话历史 21 | 可从dict生成,如 22 | h = History(**{"role":"user","content":"你好"}) 23 | 也可转换为tuple,如 24 | h.to_msy_tuple = ("human", "你好") 25 | """ 26 | role: str = Field(...) 27 | content: str = Field(...) 28 | 29 | def to_msg_tuple(self): 30 | return "ai" if self.role=="assistant" else "human", self.content 31 | -------------------------------------------------------------------------------- /muagent/codechat/__init__.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: __init__.py.py 5 | @time: 2023/11/21 下午2:01 6 | @desc: 7 | ''' -------------------------------------------------------------------------------- /muagent/codechat/code_analyzer/__init__.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: __init__.py.py 5 | @time: 2023/11/21 下午2:27 6 | @desc: 7 | ''' -------------------------------------------------------------------------------- /muagent/codechat/code_analyzer/code_dedup.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: code_dedup.py 5 | @time: 2023/11/21 下午2:27 6 | @desc: 7 | ''' 8 | # encoding: utf-8 9 | ''' 10 | @author: 温进 11 | @file: java_dedup.py 12 | @time: 2023/10/23 下午5:02 13 | @desc: 14 | ''' 15 | 16 | 17 | class CodeDedup: 18 | def __init__(self): 19 | pass 20 | 21 | def dedup(self, code_dict): 22 | code_dict = self.exact_dedup(code_dict) 23 | return code_dict 24 | 25 | def exact_dedup(self, code_dict): 26 | res = {} 27 | for fp, code_text in code_dict.items(): 28 | if code_text not in res.values(): 29 | res[fp] = code_text 30 | 31 | return res -------------------------------------------------------------------------------- /muagent/codechat/code_analyzer/code_preprocess.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: code_preprocess.py 5 | @time: 2023/11/21 下午2:28 6 | @desc: 7 | ''' 8 | 9 | class CodePreprocessor: 10 | def __init__(self): 11 | pass 12 | 13 | def preprocess(self, code_dict): 14 | return code_dict -------------------------------------------------------------------------------- /muagent/codechat/code_analyzer/code_static_analysis.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: code_static_analysis.py 5 | @time: 2023/11/21 下午2:28 6 | @desc: 7 | ''' 8 | from muagent.codechat.code_analyzer.language_static_analysis import * 9 | 10 | class CodeStaticAnalysis: 11 | def __init__(self, language): 12 | self.language = language 13 | 14 | def analyze(self, code_dict): 15 | ''' 16 | analyze code 17 | @param code_list: 18 | @return: 19 | ''' 20 | if self.language == 'java': 21 | analyzer = JavaStaticAnalysis() 22 | else: 23 | raise ValueError('language should be one of [java]') 24 | 25 | analyze_res = analyzer.analyze(code_dict) 26 | return analyze_res 27 | -------------------------------------------------------------------------------- /muagent/codechat/code_analyzer/language_static_analysis/__init__.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: __init__.py.py 5 | @time: 2023/11/21 下午4:24 6 | @desc: 7 | ''' 8 | 9 | from .java_static_analysis import JavaStaticAnalysis 10 | 11 | 12 | __all__ = [ 13 | 'JavaStaticAnalysis' 14 | ] -------------------------------------------------------------------------------- /muagent/codechat/code_crawler/__init__.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: __init__.py.py 5 | @time: 2023/11/21 下午2:02 6 | @desc: 7 | ''' 8 | from .zip_crawler import ZipCrawler 9 | from .dir_crawler import DirCrawler 10 | 11 | 12 | __all__ = [ 13 | 'ZipCrawler', 14 | 'DirCrawler' 15 | ] 16 | -------------------------------------------------------------------------------- /muagent/codechat/code_crawler/dir_crawler.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: dir_crawler.py 5 | @time: 2023/11/22 下午2:54 6 | @desc: 7 | ''' 8 | from loguru import logger 9 | import os 10 | import glob 11 | 12 | 13 | class DirCrawler: 14 | @staticmethod 15 | def crawl(path: str, suffix: str): 16 | ''' 17 | read local java file in path 18 | > path: path to crawl, must be absolute path like A/B/C 19 | < dict of java code string 20 | ''' 21 | java_file_list = glob.glob('{path}{sep}**{sep}*.{suffix}'.format(path=path, sep=os.path.sep, suffix=suffix), 22 | recursive=True) 23 | java_code_dict = {} 24 | 25 | logger.info(path) 26 | logger.info('number of file={}'.format(len(java_file_list))) 27 | logger.info(java_file_list) 28 | 29 | for java_file in java_file_list: 30 | with open(java_file, encoding="utf-8") as f: 31 | java_code = ''.join(f.readlines()) 32 | java_code_dict[java_file] = java_code 33 | return java_code_dict 34 | 35 | 36 | if __name__ == '__main__': 37 | path = '/Users/bingxu/Desktop/工作/大模型/chatbot/test_code_repo/middleware-alipay-starters-parent' 38 | suffix = 'java' 39 | DirCrawler.crawl(path, suffix) -------------------------------------------------------------------------------- /muagent/codechat/code_crawler/zip_crawler.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: zip_crawler.py 5 | @time: 2023/11/21 下午2:02 6 | @desc: 7 | ''' 8 | from loguru import logger 9 | 10 | import zipfile 11 | from muagent.codechat.code_crawler.dir_crawler import DirCrawler 12 | 13 | 14 | class ZipCrawler: 15 | @staticmethod 16 | def crawl(zip_file, output_path, suffix): 17 | ''' 18 | unzip to output_path 19 | @param zip_file: 20 | @param output_path: 21 | @return: 22 | ''' 23 | logger.info(f'output_path={output_path}') 24 | print(f'output_path={output_path}') 25 | with zipfile.ZipFile(zip_file, 'r') as z: 26 | z.extractall(output_path) 27 | 28 | code_dict = DirCrawler.crawl(output_path, suffix) 29 | return code_dict 30 | 31 | 32 | -------------------------------------------------------------------------------- /muagent/codechat/code_search/__init__.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: __init__.py.py 5 | @time: 2023/11/21 下午2:35 6 | @desc: 7 | ''' -------------------------------------------------------------------------------- /muagent/codechat/code_search/tagger.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: tagger.py 5 | @time: 2023/11/24 下午1:32 6 | @desc: 7 | ''' 8 | import re 9 | from loguru import logger 10 | 11 | 12 | class Tagger: 13 | def __init__(self): 14 | pass 15 | 16 | def generate_tag_query(self, query): 17 | ''' 18 | generate tag from query 19 | ''' 20 | # simple extract english 21 | tag_list = re.findall(r'[a-zA-Z\_\.]+', query) 22 | tag_list = list(set(tag_list)) 23 | tag_list = self.filter_tag_list(tag_list) 24 | return tag_list 25 | 26 | def filter_tag_list(self, tag_list): 27 | ''' 28 | filter out tag 29 | @param tag_list: 30 | @return: 31 | ''' 32 | res = [] 33 | for tag in tag_list: 34 | if tag in ['java', 'python']: 35 | continue 36 | res.append(tag) 37 | return res 38 | 39 | 40 | -------------------------------------------------------------------------------- /muagent/codechat/codebase_handler/__init__.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: __init__.py.py 5 | @time: 2023/11/21 下午2:07 6 | @desc: 7 | ''' -------------------------------------------------------------------------------- /muagent/connector/__init__.py: -------------------------------------------------------------------------------- 1 | from .configs import PHASE_CONFIGS 2 | 3 | 4 | 5 | PHASE_LIST = list(PHASE_CONFIGS.keys()) 6 | 7 | __all__ = [ 8 | "PHASE_CONFIGS" 9 | ] -------------------------------------------------------------------------------- /muagent/connector/agents/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_agent import BaseAgent 2 | from .react_agent import ReactAgent 3 | from .executor_agent import ExecutorAgent 4 | from .selector_agent import SelectorAgent 5 | 6 | __all__ = [ 7 | "BaseAgent", "ReactAgent", "ExecutorAgent", "SelectorAgent" 8 | ] -------------------------------------------------------------------------------- /muagent/connector/antflow/__init__.py: -------------------------------------------------------------------------------- 1 | from .flow import AgentFlow, PhaseFlow, ChainFlow 2 | 3 | 4 | 5 | __all__ = [ 6 | "AgentFlow", "PhaseFlow", "ChainFlow" 7 | ] -------------------------------------------------------------------------------- /muagent/connector/chains/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_chain import BaseChain 2 | 3 | __all__ = [ 4 | "BaseChain" 5 | ] -------------------------------------------------------------------------------- /muagent/connector/chains/chains.py: -------------------------------------------------------------------------------- 1 | from typing import List 2 | from loguru import logger 3 | from muagent.connector.agents import BaseAgent 4 | from .base_chain import BaseChain 5 | 6 | 7 | 8 | 9 | class ExecutorRefineChain(BaseChain): 10 | 11 | def __init__(self, agents: List[BaseAgent], do_code_exec: bool = False) -> None: 12 | super().__init__(agents, do_code_exec) 13 | -------------------------------------------------------------------------------- /muagent/connector/configs/__init__.py: -------------------------------------------------------------------------------- 1 | from .agent_config import AGETN_CONFIGS 2 | from .chain_config import CHAIN_CONFIGS 3 | from .phase_config import PHASE_CONFIGS 4 | from .prompt_config import * 5 | 6 | __all__ = [ 7 | "AGETN_CONFIGS", "CHAIN_CONFIGS", "PHASE_CONFIGS", 8 | "BASE_PROMPT_CONFIGS", "EXECUTOR_PROMPT_CONFIGS", "SELECTOR_PROMPT_CONFIGS", "BASE_NOTOOLPROMPT_CONFIGS", 9 | "CODE2DOC_GROUP_PROMPT_CONFIGS", "CODE2DOC_PROMPT_CONFIGS", "CODE2TESTS_PROMPT_CONFIGS" 10 | ] -------------------------------------------------------------------------------- /muagent/connector/memory/__init__.py: -------------------------------------------------------------------------------- 1 | from .hierarchical_memory_manager import HierarchicalMemoryManager 2 | 3 | __all__ = [ 4 | "HierarchicalMemoryManager" 5 | ] -------------------------------------------------------------------------------- /muagent/connector/phase/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_phase import BasePhase 2 | 3 | __all__ = ["BasePhase"] -------------------------------------------------------------------------------- /muagent/connector/prompt_manager/__init__.py: -------------------------------------------------------------------------------- 1 | from .prompt_manager import PromptManager 2 | from .extend_manager import * -------------------------------------------------------------------------------- /muagent/connector/schema/__init__.py: -------------------------------------------------------------------------------- 1 | from .memory import Memory 2 | from .general_schema import * 3 | from .message import Message 4 | 5 | __all__ = [ 6 | "Memory", "ActionStatus", "Doc", "CodeDoc", "Task", "LogVerboseEnum", 7 | "Env", "Role", "ChainConfig", "AgentConfig", "PhaseConfig", "Message", 8 | "load_role_configs", "load_chain_configs", "load_phase_configs" 9 | ] -------------------------------------------------------------------------------- /muagent/db_handler/__init__.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: __init__.py.py 5 | @time: 2023/11/16 下午3:15 6 | @desc: 7 | ''' 8 | 9 | from .graph_db_handler import NebulaHandler, NetworkxHandler, AliYunSLSHandler, GeaBaseHandler, GBHandler 10 | from .vector_db_handler import LocalFaissHandler, TbaseHandler, ChromaHandler 11 | from .db import _engine, Base 12 | 13 | __all__ = [ 14 | "GBHandler", "NebulaHandler", "NetworkxHandler", "GeaBaseHandler", 15 | "ChromaHandler", "TbaseHandler", "LocalFaissHandler", 16 | "AliYunSLSHandler" 17 | ] 18 | 19 | 20 | def create_tables(): 21 | Base.metadata.create_all(bind=_engine) 22 | 23 | def reset_tables(): 24 | Base.metadata.drop_all(bind=_engine) 25 | create_tables() 26 | 27 | 28 | def check_tables_exist(table_name) -> bool: 29 | table_exist = _engine.dialect.has_table(_engine.connect(), table_name, schema=None) 30 | return table_exist 31 | 32 | def table_init(): 33 | if (not check_tables_exist("knowledge_base")) or (not check_tables_exist ("knowledge_file")) or \ 34 | (not check_tables_exist ("code_base")): 35 | create_tables() 36 | -------------------------------------------------------------------------------- /muagent/db_handler/db.py: -------------------------------------------------------------------------------- 1 | from contextlib import contextmanager 2 | from sqlalchemy.engine import create_engine 3 | from sqlalchemy.ext.declarative import declarative_base 4 | from sqlalchemy.orm import sessionmaker 5 | 6 | from muagent.base_configs.env_config import SQLALCHEMY_DATABASE_URI 7 | # from configs.model_config import SQLALCHEMY_DATABASE_URI 8 | 9 | 10 | _engine = create_engine(SQLALCHEMY_DATABASE_URI) 11 | 12 | session_factory = sessionmaker(bind=_engine) 13 | 14 | Base = declarative_base() 15 | 16 | 17 | 18 | def init_session(): 19 | session = session_factory() 20 | 21 | try: 22 | yield session 23 | finally: 24 | try: 25 | session.commit() 26 | except Exception as e: 27 | session.rollback() 28 | raise e 29 | finally: 30 | session.close() 31 | 32 | 33 | 34 | def with_session(func): 35 | def wrapper(*args, **kwargs): 36 | session = session_factory() 37 | try: 38 | return func(session, *args, **kwargs) 39 | finally: 40 | try: 41 | session.commit() 42 | except Exception as e: 43 | session.rollback() 44 | raise e 45 | finally: 46 | session.close() 47 | return wrapper 48 | 49 | 50 | @contextmanager 51 | def session_scope(): 52 | """上下文管理器用于自动获取 Session, 避免错误""" 53 | session = session_factory(autoflush=True) 54 | try: 55 | session.commit() 56 | except Exception as e: 57 | session.rollback() 58 | raise e 59 | finally: 60 | session.close() 61 | -------------------------------------------------------------------------------- /muagent/db_handler/graph_db_handler/__init__.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: __init__.py.py 5 | @time: 2023/11/20 下午3:07 6 | @desc: 7 | ''' 8 | from .base_gb_handler import GBHandler 9 | from .nebula_handler import NebulaHandler 10 | from .networkx_handler import NetworkxHandler 11 | from .aliyun_sls_hanlder import AliYunSLSHandler 12 | from .geabase_handler import GeaBaseHandler 13 | 14 | 15 | __all__ = [ 16 | "GBHandler", "NebulaHandler", "NetworkxHandler", "GeaBaseHandler", 17 | "AliYunSLSHandler" 18 | ] -------------------------------------------------------------------------------- /muagent/db_handler/sql_db_hanlder/__init__.py: -------------------------------------------------------------------------------- 1 | from .sqlalchemy_handler import SqlalchemyHandler 2 | 3 | __all__ = [ 4 | "SqlalchemyHandler" 5 | ] -------------------------------------------------------------------------------- /muagent/db_handler/utils.py: -------------------------------------------------------------------------------- 1 | 2 | def deduplicate_dict(dict_list: list = []): 3 | seen = set() 4 | unique_dicts = [] 5 | 6 | for d in dict_list: 7 | # 使用 frozenset 进行较快的哈希,并避免重复转换 8 | d_tuple = tuple(sorted(d.items())) 9 | if d_tuple not in seen: 10 | seen.add(d_tuple) 11 | unique_dicts.append(d) 12 | 13 | return unique_dicts -------------------------------------------------------------------------------- /muagent/db_handler/vector_db_handler/__init__.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: __init__.py.py 5 | @time: 2023/11/20 下午3:08 6 | @desc: 7 | ''' 8 | 9 | from .chroma_handler import ChromaHandler 10 | from .tbase_handler import TbaseHandler 11 | from .local_faiss_handler import LocalFaissHandler 12 | 13 | __all__ = [ 14 | "ChromaHandler", "TbaseHandler", "LocalFaissHandler" 15 | ] -------------------------------------------------------------------------------- /muagent/httpapis/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/httpapis/__init__.py -------------------------------------------------------------------------------- /muagent/httpapis/ekg_construct/__init__.py: -------------------------------------------------------------------------------- 1 | from .api import create_api 2 | 3 | 4 | __all__ = [ 5 | "create_api" 6 | ] -------------------------------------------------------------------------------- /muagent/llm_models/__init__.py: -------------------------------------------------------------------------------- 1 | from .openai_model import getExtraModel, getChatModelFromConfig, CustomLLMModel 2 | from .llm_config import LLMConfig, EmbedConfig 3 | 4 | 5 | __all__ = [ 6 | "getExtraModel", "getChatModelFromConfig", "CustomLLMModel", 7 | "LLMConfig", "EmbedConfig" 8 | ] -------------------------------------------------------------------------------- /muagent/llm_models/embeddings/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/llm_models/embeddings/__init__.py -------------------------------------------------------------------------------- /muagent/llm_models/llm_shemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel, Field 2 | from typing import List, Dict, Optional, Union 3 | from enum import Enum 4 | 5 | 6 | 7 | class ChatMessage(BaseModel): 8 | role: str 9 | content: str 10 | 11 | 12 | class FunctionCallData(BaseModel): 13 | name: str 14 | arguments: Union[str, dict] 15 | 16 | 17 | class ToolCall(BaseModel): 18 | id: Optional[Union[str, int]] = None 19 | type: str = "function" 20 | function: FunctionCallData 21 | 22 | 23 | class LLMOuputMessage(BaseModel): 24 | content: Optional[str] = None 25 | role: str 26 | tool_calls: List[ToolCall] = [] 27 | 28 | 29 | class Choice(BaseModel): 30 | finish_reason: str 31 | index: int = 0 32 | message: LLMOuputMessage 33 | 34 | 35 | class UsageData(BaseModel): 36 | completion_tokens: int 37 | prompt_tokens: int 38 | total_token: int 39 | 40 | 41 | class LLMResponse(BaseModel): 42 | choices: List[Choice] 43 | created: int = 0 44 | id: str 45 | model: str 46 | object: str 47 | usage: Optional[UsageData] = None 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /muagent/memory_manager/__init__.py: -------------------------------------------------------------------------------- 1 | from .hierarchical_memory_manager import HierarchicalMemoryManager 2 | from .base_memory_manager import BaseMemoryManager 3 | from .local_memory_manager import LocalMemoryManager 4 | from .tbase_memory_manager import TbaseMemoryManager 5 | 6 | 7 | 8 | __all__ = [ 9 | "BaseMemoryManager", 10 | "LocalMemoryManager", 11 | "TbaseMemoryManager", 12 | "HierarchicalMemoryManager" 13 | ] -------------------------------------------------------------------------------- /muagent/prompt_manager/__init__.py: -------------------------------------------------------------------------------- 1 | from .base_prompt_manager import BasePromptManager 2 | from .common_prompt_manager import CommonPromptManager 3 | 4 | 5 | __all__ = [ 6 | "BasePromptManager", 7 | "CommonPromptManager" 8 | ] -------------------------------------------------------------------------------- /muagent/prompt_manager/base.py: -------------------------------------------------------------------------------- 1 | from .language.en import * 2 | from .language.zh import * 3 | 4 | 5 | TITLE_CONFIGS_LANGUAGE = { 6 | "en": EN_TITLE_CONFIGS, 7 | "zh": ZH_TITLE_CONFIGS, 8 | } 9 | 10 | TITLE_EDGES_LANGUAGE = { 11 | "en": EN_TITLE_EDGES, 12 | "zh": ZH_TITLE_EDGES, 13 | } 14 | 15 | TITLE_FORMAT_LANGUAGE = { 16 | "en": EN_TITLE_FORMAT, 17 | "zh": ZH_TITLE_FORMAT 18 | } 19 | 20 | TITLE_LANGUAGE = { 21 | "en": EN_TITLES, 22 | "zh": ZH_TITLES 23 | } 24 | 25 | ZERO_TITLES_LANGUAGE = { 26 | "en": EN_ZERO_TITLES, 27 | "zh": ZH_ZERO_TITLES, 28 | } 29 | COMMON_TEXT_LANGUAGE = { 30 | "en": EN_COMMON_TEXT, 31 | "zh": ZH_COMMON_TEXT 32 | } -------------------------------------------------------------------------------- /muagent/prompt_manager/language/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/prompt_manager/language/__init__.py -------------------------------------------------------------------------------- /muagent/retrieval/__init__.py: -------------------------------------------------------------------------------- 1 | # from .base_retrieval import * 2 | 3 | # __all__ = [ 4 | # "IMRertrieval", "BaseDocRetrieval", "BaseCodeRetrieval", "BaseSearchRetrieval" 5 | # ] -------------------------------------------------------------------------------- /muagent/retrieval/document_loaders/__init__.py: -------------------------------------------------------------------------------- 1 | from .json_loader import JSONLoader 2 | from .jsonl_loader import JSONLLoader 3 | 4 | __all__ = [ 5 | "JSONLoader", "JSONLLoader" 6 | ] -------------------------------------------------------------------------------- /muagent/retrieval/in_memory.py: -------------------------------------------------------------------------------- 1 | """Simple in memory docstore in the form of a dict.""" 2 | from typing import Dict, List, Optional, Union 3 | 4 | from langchain_community.docstore.base import AddableMixin, Docstore 5 | from langchain_community.docstore.document import Document 6 | 7 | 8 | class InMemoryDocstore(Docstore, AddableMixin): 9 | """Simple in memory docstore in the form of a dict.""" 10 | 11 | def __init__(self, _dict: Optional[Dict[str, Document]] = None): 12 | """Initialize with dict.""" 13 | self._dict = _dict if _dict is not None else {} 14 | 15 | def add(self, texts: Dict[str, Document]) -> None: 16 | """Add texts to in memory dictionary. 17 | 18 | Args: 19 | texts: dictionary of id -> document. 20 | 21 | Returns: 22 | None 23 | """ 24 | overlapping = set(texts).intersection(self._dict) 25 | if overlapping: 26 | raise ValueError(f"Tried to add ids that already exist: {overlapping}") 27 | self._dict = {**self._dict, **texts} 28 | 29 | def delete(self, ids: List) -> None: 30 | """Deleting IDs from in memory dictionary.""" 31 | overlapping = set(ids).intersection(self._dict) 32 | if not overlapping: 33 | raise ValueError(f"Tried to delete ids that does not exist: {ids}") 34 | for _id in ids: 35 | self._dict.pop(_id) 36 | 37 | def search(self, search: str) -> Union[str, Document]: 38 | """Search via direct lookup. 39 | 40 | Args: 41 | search: id of a document to search for. 42 | 43 | Returns: 44 | Document if found, else error message. 45 | """ 46 | if search not in self._dict: 47 | return f"ID {search} not found." 48 | else: 49 | return self._dict[search] 50 | -------------------------------------------------------------------------------- /muagent/retrieval/text_splitter/__init__.py: -------------------------------------------------------------------------------- 1 | from .langchain_splitter import LCTextSplitter 2 | 3 | __all__ = ["LCTextSplitter"] -------------------------------------------------------------------------------- /muagent/retrieval/text_splitter/utils.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/retrieval/text_splitter/utils.py -------------------------------------------------------------------------------- /muagent/retrieval/utils.py: -------------------------------------------------------------------------------- 1 | import os 2 | from functools import lru_cache 3 | from langchain_huggingface import HuggingFaceEmbeddings 4 | from langchain.embeddings.base import Embeddings 5 | 6 | # from configs.model_config import embedding_model_dict 7 | from loguru import logger 8 | 9 | 10 | @lru_cache(1) 11 | def load_embeddings(model: str, device: str, embedding_model_dict: dict): 12 | embeddings = HuggingFaceEmbeddings(model_name=embedding_model_dict[model], 13 | model_kwargs={'device': device}) 14 | return embeddings 15 | 16 | 17 | @lru_cache(1) 18 | def load_embeddings_from_path(model_path: str, device: str, langchain_embeddings: Embeddings = None): 19 | if langchain_embeddings: 20 | return langchain_embeddings 21 | 22 | embeddings = HuggingFaceEmbeddings(model_name=model_path, 23 | model_kwargs={'device': device}) 24 | return embeddings 25 | 26 | -------------------------------------------------------------------------------- /muagent/sandbox/__init__.py: -------------------------------------------------------------------------------- 1 | from .basebox import CodeBoxResponse 2 | from .pycodebox import PyCodeBox 3 | from .nbclient import NBClientBox, NoteBookExecutor 4 | 5 | __all__ = [ 6 | "CodeBoxResponse", "PyCodeBox", "NBClientBox" 7 | ] -------------------------------------------------------------------------------- /muagent/schemas/__init__.py: -------------------------------------------------------------------------------- 1 | from .message import Message 2 | from .memory import Memory 3 | from .agent_config import PromptConfig, AgentConfig 4 | from .project_config import ProjectConfig, EKGProjectConfig 5 | from .models import LLMConfig, ModelConfig 6 | 7 | 8 | __all__ = [ 9 | "Message", "Memory", 10 | "PromptConfig", "AgentConfig", "LLMConfig", "ModelConfig", 11 | "EKGProjectConfig", "ProjectConfig", 12 | ] 13 | -------------------------------------------------------------------------------- /muagent/schemas/apis/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/schemas/apis/__init__.py -------------------------------------------------------------------------------- /muagent/schemas/common/__init__.py: -------------------------------------------------------------------------------- 1 | from .auto_extract_graph_schema import * 2 | from .actions import * 3 | from .log import LogVerboseEnum 4 | 5 | __all__ = [ 6 | "GNodeAbs", "GEdgeAbs", "GRelationAbs", "Attribute", 7 | "GNode", "GEdge", "Graph", "GEdgeRequst", "GNodeRequest", "GRelation", 8 | "ThemeEnums", "GbaseExecStatus", 9 | 10 | "ActionStatus", 11 | "LogVerboseEnum", 12 | ] -------------------------------------------------------------------------------- /muagent/schemas/common/log.py: -------------------------------------------------------------------------------- 1 | from enum import Enum 2 | from typing import Union 3 | 4 | 5 | class LogVerboseEnum(Enum): 6 | Log0Level = "0" # don't print log 7 | Log1Level = "1" # print level-1 log 8 | Log2Level = "2" # print level-2 log 9 | Log3Level = "3" # print level-3 log 10 | 11 | def __eq__(self, other): 12 | if isinstance(other, str): 13 | return self.value.lower() == other.lower() 14 | if isinstance(other, LogVerboseEnum): 15 | return self.value == other.value 16 | return False 17 | 18 | def __ge__(self, other): 19 | if isinstance(other, LogVerboseEnum): 20 | return int(self.value) >= int(other.value) 21 | if isinstance(other, str): 22 | return int(self.value) >= int(other) 23 | return NotImplemented 24 | 25 | def __le__(self, other): 26 | if isinstance(other, LogVerboseEnum): 27 | return int(self.value) <= int(other.value) 28 | if isinstance(other, str): 29 | return int(self.value) <= int(other) 30 | return NotImplemented 31 | 32 | @classmethod 33 | def ge(self, enum_value: 'LogVerboseEnum', other: Union[str, 'LogVerboseEnum']): 34 | return enum_value <= other 35 | 36 | @classmethod 37 | def le(self, enum_value: 'LogVerboseEnum', other: Union[str, 'LogVerboseEnum']): 38 | return enum_value <= other -------------------------------------------------------------------------------- /muagent/schemas/db/__init__.py: -------------------------------------------------------------------------------- 1 | from .db_config import DBConfig, GBConfig, VBConfig, TBConfig, SLSConfig 2 | 3 | 4 | __all__ = [ 5 | "DBConfig", "GBConfig", "VBConfig", "TBConfig", "SLSConfig" 6 | ] -------------------------------------------------------------------------------- /muagent/schemas/db/db_config.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import List, Dict 3 | 4 | 5 | 6 | class DBConfig(BaseModel): 7 | db_type: str 8 | extra_kwargs: Dict = {} 9 | 10 | 11 | class GBConfig(BaseModel): 12 | gb_type: str 13 | extra_kwargs: Dict = {} 14 | 15 | 16 | class TBConfig(BaseModel): 17 | tb_type: str 18 | index_name: str 19 | host: str 20 | port: str 21 | username: str 22 | password: str 23 | extra_kwargs: Dict = {} 24 | 25 | 26 | class VBConfig(BaseModel): 27 | vb_type: str 28 | kb_root_path: str = None 29 | extra_kwargs: Dict = {} 30 | 31 | 32 | class SLSConfig(BaseModel): 33 | sls_type: str 34 | extra_kwargs: Dict = {} -------------------------------------------------------------------------------- /muagent/schemas/ekg/__init__.py: -------------------------------------------------------------------------------- 1 | from .ekg_graph import * 2 | from .ekg_create import * 3 | 4 | __all__ = [ 5 | "EKGEdgeSchema", "EKGNodeSchema", 6 | "EKGTaskNodeSchema", "EKGIntentNodeSchema", "EKGAnalysisNodeSchema", "EKGScheduleNodeSchema", "EKGPhenomenonNodeSchema", 7 | "EKGToolTypeSchema", "EKGToolSchema", "EKGAgentSchema", 8 | "EKGNodeTbaseSchema", "EKGEdgeTbaseSchema", "EKGTbaseData", 9 | "EKGGraphSlsSchema", "EKGSlsData", 10 | "SHAPE2TYPE", "TYPE2SCHEMA", 11 | "YuqueDslNodeData", "YuqueDslEdgeData", "YuqueDslDatas", 12 | 13 | "EKGIntentResp", 14 | ] -------------------------------------------------------------------------------- /muagent/schemas/ekg/ekg_create.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel 2 | from typing import List, Dict 3 | from enum import Enum 4 | 5 | 6 | 7 | class EKGIntentResp(BaseModel): 8 | intent_leaf_nodes: List[str] 9 | intent_nodes: List[str] 10 | 11 | -------------------------------------------------------------------------------- /muagent/schemas/kb/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/schemas/kb/__init__.py -------------------------------------------------------------------------------- /muagent/schemas/kb/file_schema.py: -------------------------------------------------------------------------------- 1 | import os 2 | from muagent.utils.path_utils import get_file_path, get_LoaderClass, SUPPORTED_EXTS 3 | # from configs.model_config import KB_ROOT_PATH 4 | from loguru import logger 5 | 6 | 7 | class DocumentFile: 8 | def __init__( 9 | self, filename: str, knowledge_base_name: str, kb_root_path: str) -> None: 10 | self.kb_name = knowledge_base_name 11 | self.filename = filename 12 | self.filename = os.path.basename(filename) 13 | self.ext = os.path.splitext(filename)[-1].lower() 14 | self.kb_root_path = kb_root_path 15 | if self.ext not in SUPPORTED_EXTS: 16 | raise ValueError(f"暂未支持的文件格式 {self.ext}") 17 | self.filepath = get_file_path(knowledge_base_name, self.filename, kb_root_path) 18 | self.docs = None 19 | self.document_loader_name = get_LoaderClass(self.ext) 20 | 21 | # TODO: 增加依据文件格式匹配text_splitter 22 | self.text_splitter_name = None -------------------------------------------------------------------------------- /muagent/schemas/models/__init__.py: -------------------------------------------------------------------------------- 1 | from .model import ModelConfig, LLMConfig 2 | from .llm_shemas import * 3 | 4 | 5 | __all__ = [ 6 | "ModelConfig", "LLMConfig" 7 | 8 | "ChatMessage", "FunctionCallData", "ToolCall", "LLMOuputMessage", 9 | "Choice", "UsageData", "LLMResponse", 10 | 11 | ] -------------------------------------------------------------------------------- /muagent/schemas/models/llm_shemas.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel, Field 2 | from typing import List, Dict, Optional, Union 3 | from enum import Enum 4 | 5 | 6 | 7 | class ChatMessage(BaseModel): 8 | role: str 9 | content: str 10 | 11 | 12 | class FunctionCallData(BaseModel): 13 | name: str 14 | arguments: Union[str, dict] 15 | 16 | 17 | class ToolCall(BaseModel): 18 | id: Optional[Union[str, int]] = None 19 | type: str = "function" 20 | function: FunctionCallData 21 | 22 | 23 | class LLMOuputMessage(BaseModel): 24 | content: Optional[str] = None 25 | role: str 26 | tool_calls: List[ToolCall] = [] 27 | 28 | 29 | class Choice(BaseModel): 30 | finish_reason: str 31 | index: int = 0 32 | message: LLMOuputMessage 33 | 34 | 35 | class UsageData(BaseModel): 36 | completion_tokens: int 37 | prompt_tokens: int 38 | total_token: int 39 | 40 | 41 | class LLMResponse(BaseModel): 42 | choices: List[Choice] 43 | created: int = 0 44 | id: str 45 | model: str 46 | object: str 47 | usage: Optional[UsageData] = None 48 | 49 | 50 | 51 | -------------------------------------------------------------------------------- /muagent/schemas/readme.md: -------------------------------------------------------------------------------- 1 | 2 | ## xxSchemas 3 | xxSchemas within DB, such as mysql\sls\chroma\faiss\tbase\nebula 4 | 5 | ## Config 6 | xxConfig as the class initial config 7 | 8 | ## xxResp 9 | xxResp as the http output 10 | 11 | ## xxRequest 12 | xxRequest as the http input 13 | 14 | ## xxData 15 | xxData as the function/method output 16 | 17 | ## xxParam 18 | xxParam as the function/method input 19 | -------------------------------------------------------------------------------- /muagent/service/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/service/__init__.py -------------------------------------------------------------------------------- /muagent/service/ekg_construct/__init__.py: -------------------------------------------------------------------------------- 1 | from .ekg_construct_base import EKGConstructService 2 | 3 | __all__ = [ 4 | "EKGConstructService" 5 | ] -------------------------------------------------------------------------------- /muagent/service/ekg_inference/__init__.py: -------------------------------------------------------------------------------- 1 | from .intention_router import IntentionRouter 2 | from .intention_match_rule import MatchRule 3 | 4 | 5 | __all__ = ['IntentionRouter', 'MatchRule'] 6 | -------------------------------------------------------------------------------- /muagent/service/ekg_inference/intention_match_rule.py: -------------------------------------------------------------------------------- 1 | import re 2 | import edit_distance as ed 3 | from muagent.schemas.common import GNode 4 | 5 | 6 | class MatchRule: 7 | @classmethod 8 | def edit_distance(cls, node: GNode, pattern=None, **kwargs): 9 | if len(kwargs) == 0: 10 | return -float('inf') 11 | 12 | s = list(kwargs.values())[0] 13 | desc: str = node.attributes.get('description', '') 14 | 15 | if pattern is None: 16 | return -ed.edit_distance(desc, s)[0] 17 | 18 | desc_list = re.findall(pattern, desc) 19 | if not desc_list: 20 | return -float('inf') 21 | 22 | return max([-ed.edit_distance(x, s)[0] for x in desc_list]) 23 | 24 | 25 | @classmethod 26 | def edit_distance_integer(cls, node: GNode, **kwargs): 27 | return cls.edit_distance(node, pattern='\d+', **kwargs) 28 | -------------------------------------------------------------------------------- /muagent/service/ekg_reasoning/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/service/ekg_reasoning/__init__.py -------------------------------------------------------------------------------- /muagent/service/ekg_reasoning/src/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/service/ekg_reasoning/src/__init__.py -------------------------------------------------------------------------------- /muagent/service/ekg_reasoning/src/geabase_handler/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/service/ekg_reasoning/src/geabase_handler/__init__.py -------------------------------------------------------------------------------- /muagent/service/ekg_reasoning/src/graph_search/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/service/ekg_reasoning/src/graph_search/__init__.py -------------------------------------------------------------------------------- /muagent/service/ekg_reasoning/src/graph_search/call_old_fuction.py: -------------------------------------------------------------------------------- 1 | # lingsi 游走推理服务 old 2 | import json 3 | import requests 4 | # import logging 5 | from ..utils.logger import logging 6 | import copy 7 | import sys 8 | import os 9 | 10 | # logger = logging.getLogger() 11 | # logging.basicConfig(level=logging.DEBUG) 12 | 13 | #step 1 retriver 14 | 15 | def call_old_fuction( 16 | 17 | params_string 18 | ): 19 | 20 | url =os.environ['oldfunction_url'] 21 | 22 | headers = { 23 | 'Content-Type': 'application/json;charset=utf-8', 24 | 'MPS-app-name': 'test', 25 | 'MPS-http-version': '1.0' 26 | } 27 | 28 | 29 | 30 | 31 | 32 | if type(params_string) == str: 33 | params_string = json.loads(params_string) 34 | 35 | body = { 36 | 'features': { 37 | 'query': json.dumps(params_string,ensure_ascii=False) 38 | } 39 | } 40 | r = requests.post(url, json=body, headers=headers) 41 | #logger(r) 42 | # logging.info( str((r.json() )) ) 43 | output_1 = json.loads(r.json()['resultMap']['algorithmResult']) 44 | # logging.info('============算法的结果是================') 45 | # logging.info(f'结果是 {output_1}') 46 | # logging.info('============================================') 47 | return output_1 48 | 49 | 50 | if __name__ == '__main__': 51 | #配置依赖 52 | pass -------------------------------------------------------------------------------- /muagent/service/ekg_reasoning/src/graphstructure/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/service/ekg_reasoning/src/graphstructure/__init__.py -------------------------------------------------------------------------------- /muagent/service/ekg_reasoning/src/intention_recognition/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/service/ekg_reasoning/src/intention_recognition/__init__.py -------------------------------------------------------------------------------- /muagent/service/ekg_reasoning/src/memory_handler/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/service/ekg_reasoning/src/memory_handler/__init__.py -------------------------------------------------------------------------------- /muagent/service/ekg_reasoning/src/question_answer/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/service/ekg_reasoning/src/question_answer/__init__.py -------------------------------------------------------------------------------- /muagent/service/ekg_reasoning/src/utils/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/service/ekg_reasoning/src/utils/__init__.py -------------------------------------------------------------------------------- /muagent/service/ekg_reasoning/src/utils/crypt.py: -------------------------------------------------------------------------------- 1 | from cryptography.fernet import Fernet 2 | 3 | 4 | def decrypt(encryped, key): 5 | f = Fernet(key) 6 | res_bytes = f.decrypt(encryped) 7 | res_str = res_bytes.decode('utf-8') 8 | return res_str 9 | 10 | def encrypt(text: str, key): 11 | f = Fernet(key) 12 | text_bytes = bytes(text, 'utf-8') 13 | res_bytes = f.encrypt(text_bytes) 14 | return res_bytes 15 | 16 | 17 | -------------------------------------------------------------------------------- /muagent/service/ekg_reasoning/src/utils/logger.py: -------------------------------------------------------------------------------- 1 | import logging 2 | from loguru import logger as loguru_logger 3 | 4 | 5 | def get_logger(): 6 | return loguru_logger 7 | 8 | FORMAT = '[%(asctime)s %(filename)s->%(funcName)s():%(lineno)s]%(levelname)s: %(message)s' 9 | logging.basicConfig(level=logging.DEBUG, format=FORMAT) 10 | logger_loggering = logging.getLogger() 11 | return logger_loggering 12 | 13 | import os 14 | if os.environ.get("operation_mode")=="antcode": 15 | import logging 16 | FORMAT = '[%(asctime)s %(filename)s->%(funcName)s():%(lineno)s]%(levelname)s: %(message)s' 17 | logging.basicConfig(level=logging.DEBUG, format=FORMAT) 18 | else: 19 | from loguru import logger as logging 20 | 21 | 22 | if __name__ == '__main__': 23 | logger = get_logger() 24 | logger.info('hjaha') -------------------------------------------------------------------------------- /muagent/service/ekg_reasoning/src/utils/normalize.py: -------------------------------------------------------------------------------- 1 | import math 2 | import hashlib 3 | 4 | def normalize(lis): 5 | s = sum([i * i for i in lis]) 6 | if s == 0: 7 | raise ValueError('Sum of lis is 0') 8 | 9 | s_sqrt = math.sqrt(s) 10 | res = [i / s_sqrt for i in lis] 11 | return res 12 | def md5_hash(text): 13 | m = hashlib.md5() 14 | m.update(text.encode('utf-8')) 15 | return m.hexdigest() 16 | def hash_id(nodeId, sessionId='', otherstr = None): 17 | test_res = '' 18 | test_all = nodeId + sessionId 19 | test_res = test_res + (md5_hash(test_all)) 20 | if otherstr == None: 21 | return test_res 22 | else: 23 | test_res = test_res + otherstr 24 | return test_res 25 | 26 | 27 | 28 | if __name__ == '__main__': 29 | # hash_id 30 | # text = "Hello, World!" 31 | # print("MD5 Hash of '{}' is: {}".format(text, md5_hash(text))) 32 | # print(md5_hash(text)) 33 | 34 | #hash_id 35 | nodeId = "剧本杀/谁是卧底" 36 | #sessionId = 'bbbb' 37 | #otherstr = '-userInput' 38 | print(hash_id(nodeId)) -------------------------------------------------------------------------------- /muagent/service/ui_file_service/__init__.py: -------------------------------------------------------------------------------- 1 | from .document_file_cds import * 2 | from .document_base_cds import * 3 | from .code_base_cds import * 4 | 5 | __all__ = [ 6 | "add_kb_to_db", "list_kbs_from_db", "kb_exists", 7 | "load_kb_from_db", "delete_kb_from_db", "get_kb_detail", 8 | 9 | "list_docs_from_db", "add_doc_to_db", "delete_file_from_db", 10 | "delete_files_from_db", "doc_exists", "get_file_detail", 11 | 12 | "list_cbs_from_db", "add_cb_to_db", "delete_cb_from_db", 13 | "cb_exists", "get_cb_detail", 14 | ] -------------------------------------------------------------------------------- /muagent/tools/__init__.py: -------------------------------------------------------------------------------- 1 | import importlib 2 | 3 | from .base_tool import toLangchainTools, get_tool_schema, BaseToolModel 4 | from .weather import WeatherInfo, DistrictInfo 5 | from .multiplier import Multiplier 6 | from .world_time import WorldTimeGetTimezoneByArea 7 | from .abnormal_detection import KSigmaDetector 8 | from .metrics_query import MetricsQuery 9 | from .duckduckgo_search import DDGSTool 10 | from .docs_retrieval import DocRetrieval 11 | from .cb_query_tool import CodeRetrieval 12 | from .ocr_tool import BaiduOcrTool 13 | from .stock_tool import StockInfo, StockName 14 | from .codechat_tools import CodeRetrievalSingle, RelatedVerticesRetrival, Vertex2Code 15 | from .undercover import * 16 | from .werewolf import * 17 | 18 | 19 | IMPORT_TOOL = [ 20 | WeatherInfo, DistrictInfo, Multiplier, WorldTimeGetTimezoneByArea, 21 | KSigmaDetector, MetricsQuery, DDGSTool, DocRetrieval, CodeRetrieval, 22 | BaiduOcrTool, StockInfo, StockName, CodeRetrievalSingle, RelatedVerticesRetrival, Vertex2Code, 23 | ] 24 | 25 | TOOL_SETS = [tool.__name__ for tool in IMPORT_TOOL] 26 | 27 | TOOL_DICT = {tool.__name__: tool for tool in IMPORT_TOOL} 28 | 29 | 30 | __all__ = [ 31 | "toLangchainTools", "get_tool_schema", "tool_sets", "BaseToolModel" 32 | ] + TOOL_SETS 33 | 34 | 35 | def get_tool(tool_name: str) -> BaseToolModel: 36 | return BaseToolModel._from_name(tool_name) -------------------------------------------------------------------------------- /muagent/tools/abnormal_detection.py: -------------------------------------------------------------------------------- 1 | 2 | import json 3 | import os 4 | import re 5 | from pydantic import BaseModel, Field 6 | from typing import List, Dict 7 | import requests 8 | import numpy as np 9 | from loguru import logger 10 | 11 | from .base_tool import BaseToolModel 12 | 13 | 14 | 15 | class KSigmaDetector(BaseToolModel): 16 | """ 17 | Tips: 18 | default control Required, e.g. key1 is not Required/key2 is Required 19 | """ 20 | 21 | name: str = "KSigmaDetector" 22 | description: str = "Anomaly detection using K-Sigma method" 23 | 24 | class ToolInputArgs(BaseModel): 25 | """Input for KSigmaDetector.""" 26 | 27 | data: List[float] = Field(..., description="List of data points") 28 | detect_window: int = Field(default=5, description="The size of the detect window for detecting anomalies") 29 | abnormal_window: int = Field(default=3, description="The threshold for the number of abnormal points required to classify the data as abnormal") 30 | k: float = Field(default=3.0, description="the coef of k-sigma") 31 | 32 | class ToolOutputArgs(BaseModel): 33 | """Output for KSigmaDetector.""" 34 | 35 | is_abnormal: bool = Field(..., description="Indicates whether the input data is abnormal or not") 36 | 37 | @staticmethod 38 | def run(data, detect_window=5, abnormal_window=3, k=3.0): 39 | refer_data = np.array(data[-detect_window:]) 40 | detect_data = np.array(data[:-detect_window]) 41 | mean = np.mean(refer_data) 42 | std = np.std(refer_data) 43 | 44 | is_abnormal = np.sum(np.abs(detect_data - mean) > k * std) >= abnormal_window 45 | return {"is_abnormal": is_abnormal} -------------------------------------------------------------------------------- /muagent/tools/metrics_query.py: -------------------------------------------------------------------------------- 1 | 2 | import json 3 | import os 4 | import re 5 | from pydantic import BaseModel, Field 6 | from typing import List, Dict 7 | import requests 8 | import numpy as np 9 | from loguru import logger 10 | 11 | from .base_tool import BaseToolModel 12 | 13 | 14 | 15 | class MetricsQuery(BaseToolModel): 16 | name = "MetricsQuery" 17 | description = "查询机器的监控数据" 18 | 19 | class ToolInputArgs(BaseModel): 20 | machine_ip: str = Field(..., description="machine_ip") 21 | time: int = Field(..., description="time period") 22 | 23 | class ToolOutputArgs(BaseModel): 24 | """Output for MetricsQuery.""" 25 | 26 | datas: List[float] = Field(..., description="监控时序数组") 27 | 28 | @classmethod 29 | def run(cls, machine_ip, time): 30 | """excute your tool!""" 31 | data = [0.857, 2.345, 1.234, 4.567, 3.456, 9.876, 5.678, 7.890, 6.789, 8.901, 10.987, 12.345, 11.234, 14.567, 13.456, 19.876, 15.678, 17.890, 32 | 16.789, 18.901, 20.987, 22.345, 21.234, 24.567, 23.456, 29.876, 25.678, 27.890, 26.789, 28.901, 30.987, 32.345, 31.234, 34.567, 33 | 33.456, 39.876, 35.678, 37.890, 36.789, 38.901, 40.987] 34 | return data[:30] -------------------------------------------------------------------------------- /muagent/tools/multiplier.py: -------------------------------------------------------------------------------- 1 | from pydantic import BaseModel, Field 2 | from typing import List, Dict 3 | import requests 4 | from loguru import logger 5 | 6 | from .base_tool import BaseToolModel 7 | 8 | 9 | 10 | class Multiplier(BaseToolModel): 11 | """ 12 | Tips: 13 | default control Required, e.g. key1 is not Required/key2 is Required 14 | """ 15 | 16 | name: str = "Multiplier" 17 | description: str = """useful for when you need to multiply two numbers together. \ 18 | The input to this tool should be a comma separated list of numbers of length two, representing the two numbers you want to multiply together. \ 19 | For example, `1,2` would be the input if you wanted to multiply 1 by 2.""" 20 | 21 | class ToolInputArgs(BaseModel): 22 | """Input for Multiplier.""" 23 | 24 | # key: str = Field(..., description="用户在高德地图官网申请web服务API类型KEY") 25 | a: int = Field(..., description="num a") 26 | b: int = Field(..., description="num b") 27 | 28 | class ToolOutputArgs(BaseModel): 29 | """Output for Multiplier.""" 30 | 31 | res: int = Field(..., description="the result of two nums") 32 | 33 | @staticmethod 34 | def run(a, b): 35 | return a * b -------------------------------------------------------------------------------- /muagent/tools/sandbox.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/tools/sandbox.py -------------------------------------------------------------------------------- /muagent/tools/tool_datas/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/tools/tool_datas/__init__.py -------------------------------------------------------------------------------- /muagent/utils/__init__.py: -------------------------------------------------------------------------------- 1 | from .server_utils import BaseResponse, ListResponse 2 | from .common_utils import func_timer 3 | from .postprocess import replace_lt_gt 4 | 5 | __all__ = [ 6 | "BaseResponse", "ListResponse", "func_timer", 'replace_lt_gt' 7 | ] -------------------------------------------------------------------------------- /muagent/utils/nebula_cp.sh: -------------------------------------------------------------------------------- 1 | if [ -d "/usr/local/nebula/data/meta" ]; then 2 | cp -r /usr/local/nebula/data /home/user/chatbot/data/nebula_data 3 | fi -------------------------------------------------------------------------------- /muagent/utils/postprocess.py: -------------------------------------------------------------------------------- 1 | # encoding: utf-8 2 | ''' 3 | @author: 温进 4 | @file: postprocess.py 5 | @time: 2023/11/9 下午4:01 6 | @desc: 7 | ''' 8 | import html 9 | 10 | def replace_lt_gt(text: str): 11 | text = html.unescape(text) 12 | return text -------------------------------------------------------------------------------- /muagent/utils/static/__init__.py: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/utils/static/__init__.py -------------------------------------------------------------------------------- /muagent/utils/static/favicon.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/muagent/utils/static/favicon.png -------------------------------------------------------------------------------- /requirements.txt: -------------------------------------------------------------------------------- 1 | openai==1.34.0 2 | langchain==0.2.3 3 | langchain_community==0.2.4 4 | langchain_openai==0.1.8 5 | langchain_huggingface==0.0.3 6 | sentence_transformers 7 | loguru 8 | # fastapi~=0.99.1 9 | fastapi 10 | pandas 11 | jieba 12 | psutil 13 | faiss-cpu 14 | notebook 15 | chromadb==0.4.17 16 | javalang==0.13.0 17 | nebula3-python==3.8.2 18 | Pyarrow 19 | python-magic-bin; sys_platform == 'win32' 20 | SQLAlchemy==2.0.19 21 | docker 22 | edit_distance 23 | redis==5.0.1 24 | pydantic<=1.10.14 25 | aliyun-log-python-sdk==0.9.0 26 | # pydantic 27 | # duckduckgo-search 28 | urllib3==1.26.6 29 | sseclient 30 | ollama 31 | colorama 32 | pycryptodome 33 | dashscope -------------------------------------------------------------------------------- /runtime/.gitignore: -------------------------------------------------------------------------------- 1 | HELP.md 2 | target/ 3 | !.mvn/wrapper/maven-wrapper.jar 4 | !**/src/main/**/target/ 5 | !**/src/com.alipay.muagent.web.test.test/**/target/ 6 | 7 | ### STS ### 8 | .apt_generated 9 | .classpath 10 | .factorypath 11 | .project 12 | .settings 13 | .springBeans 14 | .sts4-cache 15 | 16 | ### IntelliJ IDEA ### 17 | .idea 18 | *.iws 19 | *.iml 20 | *.ipr 21 | 22 | ### NetBeans ### 23 | /nbproject/private/ 24 | /nbbuild/ 25 | /dist/ 26 | /nbdist/ 27 | /.nb-gradle/ 28 | build/ 29 | !**/src/main/**/build/ 30 | !**/src/com.alipay.muagent.web.test.test/**/build/ 31 | 32 | ### VS Code ### 33 | .vscode/ 34 | 35 | ### maven ### 36 | .mvn/ 37 | mvnw* 38 | 39 | ### log ### 40 | .logs/ 41 | *.log 42 | -------------------------------------------------------------------------------- /runtime/Dockerfile: -------------------------------------------------------------------------------- 1 | # 使用官方的OpenJDK 17镜像作为基础镜像 2 | ## docker pull maven:3.8-openjdk-17-slim 3 | FROM openjdk:17 4 | 5 | ## 创建工作目录 6 | WORKDIR /app 7 | 8 | ## 将源代码复制到工作目录 9 | COPY ./bootstrap/muagent-runtime.jar /app/ 10 | 11 | 12 | # 指定容器启动时运行的命令 13 | CMD ["java", "-jar", "/app/muagent-runtime.jar"] -------------------------------------------------------------------------------- /runtime/Dockerfile.no-package: -------------------------------------------------------------------------------- 1 | # 使用官方的OpenJDK 17镜像作为基础镜像 2 | ## docker pull maven:3.8-openjdk-17-slim 3 | FROM maven:3.8-openjdk-17-slim 4 | 5 | ## 创建工作目录 6 | WORKDIR /app 7 | 8 | ## 将源代码复制到工作目录 9 | COPY . /app/ 10 | 11 | ## 打包源代码 12 | RUN mvn package 13 | 14 | # 指定容器启动时运行的命令 15 | # CMD ["java", "-jar", "/app/bootstrap/target/muagent-runtime.jar"] 16 | CMD ["java", "-jar", "/app/bootstrap/muagent-runtime.jar"] -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/java/com/alipay/muagent/bootstrap/BootstrapApplication.java: -------------------------------------------------------------------------------- 1 | package com.alipay.muagent.bootstrap; 2 | 3 | import com.alipay.muagent.util.LoggerUtil; 4 | import org.mybatis.spring.annotation.MapperScan; 5 | import org.slf4j.Logger; 6 | import org.slf4j.LoggerFactory; 7 | import org.springframework.boot.SpringApplication; 8 | import org.springframework.boot.autoconfigure.SpringBootApplication; 9 | import org.springframework.context.annotation.ComponentScan; 10 | 11 | 12 | @SpringBootApplication 13 | @ComponentScan(basePackages = {"com.alipay.muagent"}) 14 | @MapperScan("com.alipay.muagent.service.mybatisplus.mapper") 15 | public class BootstrapApplication { 16 | 17 | private static final Logger LOGGER = LoggerFactory.getLogger(BootstrapApplication.class); 18 | 19 | public static void main(String[] args) { 20 | try { 21 | SpringApplication.run(BootstrapApplication.class, args); 22 | LoggerUtil.info(LOGGER, "Runtime Application has been started!!"); 23 | } catch (Exception e) { 24 | LoggerUtil.error(LOGGER, e, "Runtime has been failed."); 25 | } 26 | } 27 | } 28 | -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/resources/config/application-default.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=runtime 2 | 3 | logging.path=./logs 4 | logging.root=${logging.path} 5 | logging.config=classpath:log4j2-spring.xml 6 | app_name=${spring.application.name} 7 | logging.level.com.alipay.muagent=INFO 8 | server.port=8080 9 | 10 | 11 | spring.output.ansi.enabled=ALWAYS 12 | 13 | ekg.chat.url=http://ekgservice:3737/ekg/graph/ekg_migration_reasoning 14 | 15 | ekg.candidate.tools=undercover.dispatch_keyword,undercover.dispatch_position,\ 16 | undercover.judge,undercover.lijing,undercover.summary,undercover.wangpeng,\ 17 | undercover.zhangwei,undercover.show_key_information,\ 18 | werewolf.dispatch_keyword,werewolf.dispatch_position,werewolf.hangang,\ 19 | werewolf.hezixuan,werewolf.judge,werewolf.liangjun,werewolf.shenqiang,\ 20 | werewolf.zhoujie,werewolf.zhouxinyi,werewolf.zhuli,werewolf.summary -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/resources/config/application.properties: -------------------------------------------------------------------------------- 1 | spring.application.name=runtime 2 | 3 | logging.path=./logs 4 | 5 | spring.datasource.type=com.zaxxer.hikari.HikariDataSource 6 | spring.datasource.url=jdbc:mysql://mysql:3306/muagent?allowPublicKeyRetrieval=true&characterEncoding=utf-8&&useSSL=false&serverTimezone=UTC 7 | spring.datasource.username=root 8 | spring.datasource.password=root 9 | spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver 10 | 11 | mybatis-plus.mapper-locations=classpath:mapper/*.xml 12 | mybatis-plus.type-aliases-package=com.alipay.muagent.model 13 | 14 | #配置读取tool的方式:local|mysql 15 | runtime.tool.datatype=mysql 16 | -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/resources/static/avatar/hangang.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/runtime/bootstrap/src/main/resources/static/avatar/hangang.png -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/resources/static/avatar/hezixuan.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/runtime/bootstrap/src/main/resources/static/avatar/hezixuan.png -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/resources/static/avatar/liangjun.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/runtime/bootstrap/src/main/resources/static/avatar/liangjun.png -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/resources/static/avatar/lijing.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/runtime/bootstrap/src/main/resources/static/avatar/lijing.png -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/resources/static/avatar/nex.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/runtime/bootstrap/src/main/resources/static/avatar/nex.png -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/resources/static/avatar/referee.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/runtime/bootstrap/src/main/resources/static/avatar/referee.png -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/resources/static/avatar/shenqiang.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/runtime/bootstrap/src/main/resources/static/avatar/shenqiang.png -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/resources/static/avatar/wangpeng.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/runtime/bootstrap/src/main/resources/static/avatar/wangpeng.png -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/resources/static/avatar/zhangwei.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/runtime/bootstrap/src/main/resources/static/avatar/zhangwei.png -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/resources/static/avatar/zhoujie.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/runtime/bootstrap/src/main/resources/static/avatar/zhoujie.png -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/resources/static/avatar/zhouxinyi.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/runtime/bootstrap/src/main/resources/static/avatar/zhouxinyi.png -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/resources/static/avatar/zhuli.png: -------------------------------------------------------------------------------- https://raw.githubusercontent.com/codefuse-ai/CodeFuse-muAgent/ebc8c3fbc886969befb6be18d4f85787de29b086/runtime/bootstrap/src/main/resources/static/avatar/zhuli.png -------------------------------------------------------------------------------- /runtime/bootstrap/src/main/resources/static/index.html: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | 5 | Title 6 | 7 | 8 | nihao 9 | 10 | -------------------------------------------------------------------------------- /runtime/model/pom.xml: -------------------------------------------------------------------------------- 1 | 2 | 5 | 4.0.0 6 | 7 | com.alipay.muagent 8 | runtime 9 | 0.0.1-SNAPSHOT 10 | 11 | 12 | model 13 | 14 | 15 | 17 16 | 17 17 | UTF-8 18 | 19 | 20 | 21 | 22 | javax.validation 23 | validation-api 24 | 25 | 26 | 27 | com.google.code.gson 28 | gson 29 | 30 | 31 | 32 | 33 | org.projectlombok 34 | lombok 35 | 36 | 37 | 38 | 39 | com.baomidou 40 | mybatis-plus-boot-starter 41 | 42 | 43 | com.fasterxml.jackson.core 44 | jackson-annotations 45 | 46 | 47 | com.fasterxml.jackson.core 48 | jackson-databind 49 | 50 | 51 | 52 | 53 | -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/chat/ChatContent.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.chat; 6 | 7 | /** 8 | * @author renmao.rm 9 | * @version : ChatContent.java, v 0.1 2024年10月09日 下午4:31 renmao.rm Exp $ 10 | */ 11 | public class ChatContent { 12 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/chat/ChatRequest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.chat; 6 | 7 | import com.alipay.muagent.model.enums.chat.ChatTypeEnum; 8 | import com.google.gson.JsonObject; 9 | import lombok.Data; 10 | 11 | import javax.validation.constraints.NotNull; 12 | import java.util.Map; 13 | 14 | /** 15 | * @author renmao.rm 16 | * @version : ChatRequest.java, v 0.1 2024年10月09日 下午4:13 renmao.rm Exp $ 17 | */ 18 | @Data 19 | public class ChatRequest { 20 | 21 | /** 22 | * 会话ID 23 | */ 24 | @NotNull(message = "sessionId不能为空") 25 | private String sessionId; 26 | 27 | /** 28 | * agent ID 29 | */ 30 | @NotNull(message = "agentId不能为空") 31 | private String agentId; 32 | 33 | /** 34 | * 用户信息 35 | */ 36 | private String userId; 37 | 38 | /** 39 | * 流式输出协议 40 | * 不填默认:false,流式输出必须传入 true 41 | */ 42 | private Boolean stream; 43 | 44 | /** 45 | * 类型 46 | * text/card 47 | */ 48 | private ChatTypeEnum type; 49 | 50 | /** 51 | * 内容 52 | */ 53 | @NotNull(message = "content不能为空") 54 | private Map content; 55 | 56 | /** 57 | * 重试的时候需要带上提问id 58 | */ 59 | private String msgId; 60 | 61 | /** 62 | * 扩展字段 63 | */ 64 | private Map extendContext; 65 | 66 | 67 | /** 68 | * 接口调用来源 69 | */ 70 | private String callSource; 71 | 72 | /** 73 | * 上一次submit chat返回的id 74 | */ 75 | private String chatUniqueId; 76 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/chat/ChatResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.chat; 6 | 7 | import com.alipay.muagent.model.chat.content.RoleResponseContent; 8 | import com.alipay.muagent.model.chat.content.TextContent; 9 | import com.alipay.muagent.model.enums.chat.ChatTypeEnum; 10 | import lombok.Builder; 11 | import lombok.Data; 12 | 13 | import java.util.ArrayList; 14 | import java.util.List; 15 | import java.util.Map; 16 | 17 | import static com.alipay.muagent.model.enums.chat.ChatTypeEnum.role_response; 18 | import static com.alipay.muagent.model.enums.chat.ChatTypeEnum.text; 19 | 20 | /** 21 | * @author renmao.rm 22 | * @version : ChatResponse.java, v 0.1 2024年10月17日 上午10:36 renmao.rm Exp $ 23 | */ 24 | @Data 25 | @Builder 26 | public class ChatResponse { 27 | 28 | private ChatTypeEnum type; 29 | 30 | private ChatContent content; 31 | 32 | private Map extendContext; 33 | 34 | public static ChatResponse buildTextResponse(String content) { 35 | return ChatResponse.builder().type(text).content(TextContent.builder().text(content).build()).build(); 36 | } 37 | 38 | public static List buildTextResponses(String content) { 39 | List responses = new ArrayList<>(); 40 | responses.add(buildTextResponse(content)); 41 | return responses; 42 | } 43 | 44 | public static ChatResponse buildRoleResponse(RoleResponseContent role) { 45 | return ChatResponse.builder().type(role_response).content(role).build(); 46 | } 47 | 48 | public static List buildRoleResponses(RoleResponseContent role) { 49 | List responses = new ArrayList<>(); 50 | responses.add(buildRoleResponse(role)); 51 | return responses; 52 | } 53 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/chat/SessionCreateRequest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.chat; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : SessionCreateRequest.java, v 0.1 2024年10月11日 下午9:47 renmao.rm Exp $ 12 | */ 13 | @Data 14 | public class SessionCreateRequest { 15 | 16 | /** 17 | * session 过期时间 18 | */ 19 | private String expireTime; 20 | 21 | /** 22 | * 标题摘要 23 | */ 24 | private String summary; 25 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/chat/content/JsonContent.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.chat.content; 6 | 7 | import lombok.Data; 8 | 9 | import java.util.Map; 10 | 11 | /** 12 | * @author renmao.rm 13 | * @version : JsonContent.java, v 0.1 2024年10月10日 下午7:03 renmao.rm Exp $ 14 | */ 15 | @Data 16 | public class JsonContent { 17 | 18 | private Map data; 19 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/chat/content/TextContent.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.chat.content; 6 | 7 | import com.alipay.muagent.model.chat.ChatContent; 8 | import lombok.Builder; 9 | import lombok.Data; 10 | 11 | /** 12 | * @author renmao.rm 13 | * @version : TextContent.java, v 0.1 2024年10月10日 下午6:53 renmao.rm Exp $ 14 | */ 15 | @Data 16 | @Builder 17 | public class TextContent extends ChatContent { 18 | 19 | /** 20 | * 大模型对话返回内容或用户提问内容 21 | */ 22 | private String text; 23 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/connector/http/HttpParameters.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.connector.http; 6 | 7 | import lombok.AllArgsConstructor; 8 | import lombok.Builder; 9 | import lombok.Data; 10 | 11 | import java.util.Map; 12 | 13 | /** 14 | * @author renmao.rm 15 | * @version : HttpParameters.java, v 0.1 2024年10月11日 下午1:40 renmao.rm Exp $ 16 | */ 17 | @Data 18 | @Builder 19 | public class HttpParameters { 20 | 21 | private String url; 22 | 23 | private String requestMethod; 24 | 25 | /** 26 | * swagger的header类型参数 27 | */ 28 | private Map headerParameters; 29 | 30 | /** 31 | * swagger的path类型参数 32 | */ 33 | private Map pathParameters; 34 | 35 | /** 36 | * swagger的query类型参数 37 | */ 38 | private Map queryParameters; 39 | 40 | /** 41 | * swagger的body类型参数 42 | */ 43 | private String requestBody; 44 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/BaseEkgResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : BaseEkgResponse.java, v 0.1 2024年10月16日 上午11:16 renmao.rm Exp $ 12 | */ 13 | @Data 14 | public class BaseEkgResponse { 15 | 16 | private int resultCode; 17 | 18 | private String errorMsg; 19 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/EkgAlgorithmResult.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg; 6 | 7 | import lombok.Data; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * @author renmao.rm 13 | * @version : EkgAlgorithmResult.java, v 0.1 2024年10月10日 上午11:28 renmao.rm Exp $ 14 | */ 15 | @Data 16 | public class EkgAlgorithmResult { 17 | 18 | /** 19 | * 对应总线的conversationId 20 | */ 21 | private String sessionId; 22 | 23 | /** 24 | * 节点类型 25 | */ 26 | private String type; 27 | 28 | /** 29 | * 下一步的ekg节点 30 | */ 31 | private List toolPlan; 32 | 33 | /** 34 | * 关键节点信息 35 | */ 36 | private String userInteraction; 37 | 38 | /** 39 | * 如果是图执行的最后一个节点,做图总结 40 | */ 41 | private String summary; 42 | 43 | /** 44 | * 意图指导 45 | */ 46 | private String intentionRecognitionSituation; 47 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/EkgFeaturesRequest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : EkgFeaturesRequest.java, v 0.1 2024年10月16日 上午11:00 renmao.rm Exp $ 12 | */ 13 | @Data 14 | public class EkgFeaturesRequest { 15 | 16 | private EkgQueryRequest query; 17 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/EkgNode.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : EkgNode.java, v 0.1 2024年10月10日 上午11:29 renmao.rm Exp $ 12 | */ 13 | @Data 14 | public class EkgNode { 15 | 16 | /** 17 | * tool描述 18 | */ 19 | private String toolDescription; 20 | 21 | /** 22 | * 当前节点id 23 | */ 24 | private String currentNodeId; 25 | 26 | /** 27 | * 上下文 28 | */ 29 | private String memory; 30 | 31 | /** 32 | * 节点类型 33 | */ 34 | private String type; 35 | 36 | /** 37 | * 用户交互信息 38 | */ 39 | private EkgQuestionDescription questionDescription; 40 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/EkgNodeType.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Ant Group 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg; 6 | 7 | import lombok.Getter; 8 | 9 | /** 10 | * @author jikong 11 | * @version EkgNodeType.java, v 0.1 2024年10月11日 19:44 jikong 12 | */ 13 | @Getter 14 | public enum EkgNodeType { 15 | Intent("opsgptkg_intent", "意图节点"), 16 | Schedule("opsgptkg_schedule", "计划节点"), 17 | Task("opsgptkg_task", "任务节点"), 18 | Analysis("opsgptkg_analysis", "分析结论节点"), 19 | Phenomenon("opsgptkg_phenomenon", "实事现象节点"); 20 | 21 | private final String code; 22 | private final String description; 23 | 24 | EkgNodeType(String code, String description) { 25 | this.code = code; 26 | this.description = description; 27 | } 28 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/EkgQueryRequest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg; 6 | 7 | import lombok.Data; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * @author renmao.rm 13 | * @version : EkgRequest.java, v 0.1 2024年10月10日 上午11:01 renmao.rm Exp $ 14 | */ 15 | @Data 16 | public class EkgQueryRequest extends EkgSceneSessionRequest { 17 | 18 | private String startRootNodeId; 19 | 20 | /** 21 | * 为意图识别所用,意图识别时所采用的规则 22 | */ 23 | private List intentionRule; 24 | 25 | /** 26 | * 为意图识别所用,意图识别时所采用的数据 27 | */ 28 | private List intentionData; 29 | 30 | /** 31 | * 当前节点的id,第一次输入null 32 | */ 33 | private String currentNodeId; 34 | 35 | /** 36 | * 当前节点的类型 37 | */ 38 | private String type; 39 | 40 | /** 41 | * tool执行结果 42 | */ 43 | private String observation; 44 | 45 | /** 46 | * 用户回答 47 | */ 48 | private String userAnswer; 49 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/EkgQuestionContent.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg; 6 | 7 | import lombok.Data; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * @author renmao.rm 13 | * @version : EkgQuestionContent.java, v 0.1 2024年10月10日 上午11:29 renmao.rm Exp $ 14 | */ 15 | @Data 16 | public class EkgQuestionContent { 17 | 18 | /** 19 | * 问题 20 | */ 21 | private String question; 22 | 23 | /** 24 | * 可能的选项。 25 | * 注意此项在问答题的时候为None 26 | */ 27 | private List candidate; 28 | 29 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/EkgQuestionDescription.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : EkgQuestionDescription.java, v 0.1 2024年10月10日 上午11:30 renmao.rm Exp $ 12 | */ 13 | @Data 14 | public class EkgQuestionDescription { 15 | 16 | 17 | /** 18 | * 问题类型 19 | * "multipleChoice", # or "essayQuestion" 20 | */ 21 | private String questionType; 22 | 23 | /** 24 | * 问题内容 25 | */ 26 | private EkgQuestionContent questionContent; 27 | 28 | /** 29 | * 给用户展示的额外信息 30 | */ 31 | private String extraMessage; 32 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/EkgRequest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : EkgRequest.java, v 0.1 2024年10月16日 上午10:58 renmao.rm Exp $ 12 | */ 13 | @Data 14 | public class EkgRequest { 15 | 16 | public EkgRequest(EkgQueryRequest query) { 17 | this.features.setQuery(query); 18 | } 19 | 20 | private EkgFeaturesRequest features = new EkgFeaturesRequest(); 21 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/EkgResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : EkgResponse.java, v 0.1 2024年10月16日 上午11:13 renmao.rm Exp $ 12 | */ 13 | @Data 14 | public class EkgResponse extends BaseEkgResponse{ 15 | 16 | private EkgResponseResultMap resultMap; 17 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/EkgResponseResultMap.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : EkgResponseResultMap.java, v 0.1 2024年10月16日 上午11:14 renmao.rm Exp $ 12 | */ 13 | @Data 14 | public class EkgResponseResultMap extends BaseEkgResponse { 15 | 16 | private String algorithmResult; 17 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/EkgSceneSessionRequest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : EkgSceneSessionRequest.java, v 0.1 2024年10月10日 上午11:00 renmao.rm Exp $ 12 | */ 13 | @Data 14 | public class EkgSceneSessionRequest { 15 | 16 | /** 17 | * 18 | */ 19 | protected String scene; 20 | 21 | /** 22 | * 23 | */ 24 | protected String sessionId; 25 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/EkgToolResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg; 6 | 7 | import lombok.Builder; 8 | import lombok.Data; 9 | 10 | /** 11 | * @author renmao.rm 12 | * @version : EkgToolResponse.java, v 0.1 2024年10月19日 19:45 renmao.rm Exp $ 13 | */ 14 | @Data 15 | @Builder 16 | public class EkgToolResponse { 17 | 18 | private String toolResponse; 19 | 20 | private String toolKey; 21 | 22 | private String toolParam; 23 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/ExeNodeResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg; 6 | 7 | import lombok.Builder; 8 | import lombok.Data; 9 | 10 | /** 11 | * @author renmao.rm 12 | * @version : ExeNodeResponse.java, v 0.1 2024年10月10日 下午8:31 renmao.rm Exp $ 13 | */ 14 | @Data 15 | @Builder 16 | public class ExeNodeResponse { 17 | 18 | private String output; 19 | 20 | private String toolKey; 21 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/configuration/Config.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg.configuration; 6 | 7 | import lombok.Data; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * @author renmao.rm 13 | * @version : Config.java, v 0.1 2024年10月10日 下午7:24 renmao.rm Exp $ 14 | */ 15 | @Data 16 | public class Config { 17 | 18 | private String ekgUrl; 19 | 20 | private List toolKeys; 21 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/storage/GraphEdge.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Ant Group 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg.storage; 6 | 7 | import com.google.gson.annotations.SerializedName; 8 | import lombok.Data; 9 | 10 | import java.util.HashMap; 11 | import java.util.Map; 12 | 13 | /** 14 | * @author jikong 15 | * @version GraphEdge.java, v 0.1 2024年10月11日 19:32 jikong 16 | */ 17 | @Data 18 | public class GraphEdge { 19 | /** 20 | * 起点节点ID 21 | */ 22 | @SerializedName("start_id") 23 | private String startId; 24 | 25 | /** 26 | * 终点节点ID 27 | */ 28 | @SerializedName("end_id") 29 | private String endId; 30 | 31 | /** 32 | * 属性 33 | */ 34 | Map attributes = new HashMap<>(); 35 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/storage/GraphGraph.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Ant Group 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg.storage; 6 | 7 | import lombok.Data; 8 | 9 | import java.util.LinkedList; 10 | import java.util.List; 11 | 12 | /** 13 | * @author jikong 14 | * @version GraphGraph.java, v 0.1 2024年10月11日 19:34 jikong 15 | */ 16 | @Data 17 | public class GraphGraph { 18 | /** 19 | * 路径上的节点 20 | */ 21 | List nodes = new LinkedList<>(); 22 | 23 | /** 24 | * 路径上的边 25 | */ 26 | List edges = new LinkedList<>(); 27 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/storage/GraphNode.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Ant Group 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg.storage; 6 | 7 | import lombok.Data; 8 | 9 | import java.util.HashMap; 10 | import java.util.Map; 11 | 12 | /** 13 | * @author jikong 14 | * @version GraphNode.java, v 0.1 2024年10月11日 19:32 jikong 15 | */ 16 | @Data 17 | public class GraphNode { 18 | /** 19 | * 节点ID 20 | */ 21 | private String id; 22 | 23 | /** 24 | * 节点类型 25 | */ 26 | private String type; 27 | 28 | /** 29 | * 节点属性 30 | */ 31 | Map attributes = new HashMap<>(); 32 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/ekg/storage/GraphUpdateRequest.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Ant Group 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.ekg.storage; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author jikong 11 | * @version GraphUpdateRequest.java, v 0.1 2024年10月11日 19:36 jikong 12 | */ 13 | @Data 14 | public class GraphUpdateRequest { 15 | /** 16 | * 团队ID 17 | */ 18 | private String teamId; 19 | 20 | /** 21 | * 当前层级的根节点ID 22 | * 外层图谱: 团队根节点(开始节点) 23 | * 内层图谱: 计划节点 24 | */ 25 | private String rootNodeId; 26 | 27 | /** 28 | * 更新前的图 29 | */ 30 | private GraphGraph oldGraph = new GraphGraph(); 31 | 32 | /** 33 | * 更新后的图 34 | */ 35 | private GraphGraph newGraph = new GraphGraph(); 36 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/enums/chat/ChatExtendedKeyEnum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.enums.chat; 6 | 7 | /** 8 | * @author renmao.rm 9 | * @version : ChatExtendedKeyEnum.java, v 0.1 2024年10月21日 10:59 renmao.rm Exp $ 10 | */ 11 | public enum ChatExtendedKeyEnum { 12 | 13 | EKG_NODE, 14 | 15 | CHAT_UNIQUE_ID, 16 | ; 17 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/enums/chat/ChatTypeBelongingTypeEnum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.enums.chat; 6 | 7 | /** 8 | * @author renmao.rm 9 | * @version : ChatTypeBelonging.java, v 0.1 2024年10月10日 上午10:43 renmao.rm Exp $ 10 | */ 11 | public enum ChatTypeBelongingTypeEnum { 12 | 13 | REQUEST, 14 | RESPONSE, 15 | BOTH 16 | ; 17 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/enums/chat/ChatTypeEnum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.enums.chat; 6 | 7 | import lombok.Getter; 8 | 9 | import static com.alipay.muagent.model.enums.chat.ChatTypeBelongingTypeEnum.BOTH; 10 | import static com.alipay.muagent.model.enums.chat.ChatTypeBelongingTypeEnum.RESPONSE; 11 | 12 | /** 13 | * @author renmao.rm 14 | * @version : ChatTypeEnum.java, v 0.1 2024年10月09日 下午7:13 renmao.rm Exp $ 15 | */ 16 | @Getter 17 | public enum ChatTypeEnum { 18 | 19 | text("text", "文本类型", BOTH), 20 | role_response("role_response", "", RESPONSE), 21 | json("json", "json类型", BOTH), 22 | markdown("markdown", "markdown类型", RESPONSE), 23 | ; 24 | 25 | private String typeCode; 26 | 27 | private String description; 28 | 29 | private ChatTypeBelongingTypeEnum belongingTyp; 30 | 31 | ChatTypeEnum(String typeCode, String description, ChatTypeBelongingTypeEnum belongingTypeEnum) { 32 | this.typeCode = typeCode; 33 | this.description = description; 34 | this.belongingTyp = belongingTypeEnum; 35 | } 36 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/enums/ekg/ToolPlanTypeEnum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.enums.ekg; 6 | 7 | import lombok.Getter; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : ToolPlanTypeEnum.java, v 0.1 2024年10月21日 10:27 renmao.rm Exp $ 12 | */ 13 | @Getter 14 | public enum ToolPlanTypeEnum { 15 | USER_PROBLEM("userProblem"), 16 | 17 | ; 18 | 19 | private String code; 20 | 21 | ToolPlanTypeEnum(String code) { 22 | this.code = code; 23 | } 24 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/enums/scheduler/TaskSchedulerTypeEnum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.enums.scheduler; 6 | 7 | /** 8 | * @author renmao.rm 9 | * @version : TaskSchedulerTypeEnum.java, v 0.1 2024年10月11日 下午3:02 renmao.rm Exp $ 10 | */ 11 | public enum TaskSchedulerTypeEnum { 12 | COMMON, 13 | ; 14 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/enums/tool/ToolProtocolEnum.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.enums.tool; 6 | 7 | /** 8 | * @author renmao.rm 9 | * @version : ToolProtocol.java, v 0.1 2024年10月10日 下午10:07 renmao.rm Exp $ 10 | */ 11 | public enum ToolProtocolEnum { 12 | 13 | HTTP, 14 | TR, 15 | GROOVY, 16 | ; 17 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/exception/EkgToolNotFindException.java: -------------------------------------------------------------------------------- 1 | package com.alipay.muagent.model.exception; 2 | 3 | public class EkgToolNotFindException extends RuntimeException { 4 | public EkgToolNotFindException(String message) { 5 | super(message); 6 | } 7 | } 8 | -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/scheduler/SubmitTaskRequest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.scheduler; 6 | 7 | import com.alipay.muagent.model.enums.scheduler.TaskSchedulerTypeEnum; 8 | import lombok.Builder; 9 | import lombok.Data; 10 | 11 | import java.util.List; 12 | 13 | /** 14 | * @author renmao.rm 15 | * @version : SubmitTaskRequest.java, v 0.1 2024年10月10日 下午9:55 renmao.rm Exp $ 16 | */ 17 | @Data 18 | @Builder 19 | public class SubmitTaskRequest { 20 | 21 | /** 22 | * user intention 23 | */ 24 | private String intention; 25 | 26 | private String memory; 27 | 28 | private boolean ekgRequest; 29 | 30 | /** 31 | * the range of tools needed to execute 32 | */ 33 | private List tools; 34 | 35 | /** 36 | * 37 | */ 38 | private TaskSchedulerTypeEnum schedulerType; 39 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/scheduler/TaskExeResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.scheduler; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : TaskExeResponse.java, v 0.1 2024年10月10日 下午10:03 renmao.rm Exp $ 12 | */ 13 | @Data 14 | public class TaskExeResponse { 15 | 16 | private String response; 17 | 18 | private String toolKey; 19 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/shell/ShellRequest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.shell; 6 | 7 | import lombok.Data; 8 | 9 | import java.util.Map; 10 | 11 | /** 12 | * @author renmao.rm 13 | * @version : ShellRequest.java, v 0.1 2024年10月11日 上午11:05 renmao.rm Exp $ 14 | */ 15 | @Data 16 | public class ShellRequest { 17 | 18 | private Map args; 19 | 20 | private String script; 21 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/shell/ShellResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.shell; 6 | 7 | import lombok.Builder; 8 | import lombok.Data; 9 | 10 | /** 11 | * @author renmao.rm 12 | * @version : ShellResponse.java, v 0.1 2024年10月11日 上午11:05 renmao.rm Exp $ 13 | */ 14 | @Data 15 | @Builder 16 | public class ShellResponse { 17 | 18 | private String result; 19 | 20 | private String log; 21 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/TaskExeContext.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool; 6 | 7 | import com.alipay.muagent.model.scheduler.SubmitTaskRequest; 8 | import com.alipay.muagent.model.tool.callback.CallBackConfig; 9 | import com.alipay.muagent.model.tool.meta.Tool; 10 | import lombok.Data; 11 | 12 | /** 13 | * @author renmao.rm 14 | * @version : ToolExeContext.java, v 0.1 2024年10月10日 下午9:26 renmao.rm Exp $ 15 | */ 16 | @Data 17 | public class TaskExeContext { 18 | 19 | public TaskExeContext() { 20 | 21 | } 22 | 23 | public TaskExeContext(Tool tool, String intention) { 24 | this.tool = tool; 25 | this.taskRequest = SubmitTaskRequest.builder().intention(intention).build(); 26 | } 27 | 28 | private Tool tool; 29 | 30 | private SubmitTaskRequest taskRequest; 31 | 32 | private ToolExeResponse toolExeResponse; 33 | 34 | private CallBackConfig callBackConfig; 35 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/ToolExeRequest.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool; 6 | 7 | /** 8 | * @author renmao.rm 9 | * @version : ToolExeRequest.java, v 0.1 2024年10月10日 下午9:20 renmao.rm Exp $ 10 | */ 11 | public class ToolExeRequest { 12 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/ToolExeResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool; 6 | 7 | import lombok.Builder; 8 | import lombok.Data; 9 | 10 | /** 11 | * @author renmao.rm 12 | * @version : ToolExeResponse.java, v 0.1 2024年10月10日 下午9:18 renmao.rm Exp $ 13 | */ 14 | @Data 15 | @Builder 16 | public class ToolExeResponse { 17 | 18 | private String result; 19 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/ToolInvokeResponse.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : ToolInvokeResposne.java, v 0.1 2024年10月10日 下午9:47 renmao.rm Exp $ 12 | */ 13 | @Data 14 | public class ToolInvokeResponse { 15 | 16 | 17 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/callback/CallBackConfig.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool.callback; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : CallBackConfig.java, v 0.1 2024年10月10日 下午10:00 renmao.rm Exp $ 12 | */ 13 | @Data 14 | public class CallBackConfig { 15 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/meta/ApiIvkSchema.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool.meta; 6 | 7 | import com.alipay.muagent.model.tool.meta.serilizer.JsonObjectDeserializer; 8 | import com.alipay.muagent.model.tool.meta.serilizer.JsonObjectSerializer; 9 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 10 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 11 | import com.google.gson.JsonObject; 12 | import lombok.Data; 13 | 14 | import java.util.List; 15 | 16 | /** 17 | * @author renmao.rm 18 | * @version : ApiIvkSchema.java, v 0.1 2024年10月11日 上午10:22 renmao.rm Exp $ 19 | */ 20 | @Data 21 | public class ApiIvkSchema { 22 | 23 | /** 24 | * vesion 25 | */ 26 | private String openapi = "3.0.0"; 27 | 28 | /** 29 | * info 30 | */ 31 | private ApiIvkSchemaInfo info; 32 | 33 | /** 34 | * servers 35 | */ 36 | private List servers; 37 | 38 | /** 39 | * path 40 | */ 41 | private Protocols paths; 42 | 43 | /** 44 | * model 定义 45 | */ 46 | @JsonSerialize(using = JsonObjectSerializer.class) 47 | @JsonDeserialize(using = JsonObjectDeserializer.class) 48 | private JsonObject definitions; 49 | 50 | /** 51 | * 接口信息 52 | */ 53 | @JsonSerialize(using = JsonObjectSerializer.class) 54 | @JsonDeserialize(using = JsonObjectDeserializer.class) 55 | private JsonObject apis; 56 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/meta/ApiIvkSchemaInfo.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool.meta; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : ApiIvkSchemaInfo.java, v 0.1 2024年10月11日 上午10:24 renmao.rm Exp $ 12 | */ 13 | @Data 14 | public class ApiIvkSchemaInfo { 15 | 16 | /** 17 | * title 18 | */ 19 | private String title; 20 | 21 | /** 22 | * description 23 | */ 24 | private String description; 25 | 26 | /** 27 | * TODO version 是否有用 28 | */ 29 | private String version = "0.0.1"; 30 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/meta/ApiIvkSchemaServer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool.meta; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * 11 | * @author renmao.rm 12 | * @version : ApiIvkSchemaServer.java, v 0.1 2024年10月11日 上午10:54 renmao.rm Exp $ 13 | */ 14 | @Data 15 | public class ApiIvkSchemaServer { 16 | 17 | /** 18 | * url 19 | */ 20 | private String url; 21 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/meta/ManifestSchema.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool.meta; 6 | 7 | import lombok.Data; 8 | 9 | import java.util.Map; 10 | 11 | /** 12 | * @author renmao.rm 13 | * @version : ManifestSchema.java, v 0.1 2024年10月11日 上午10:19 renmao.rm Exp $ 14 | */ 15 | @Data 16 | public class ManifestSchema { 17 | 18 | /** 19 | * schema_version 20 | */ 21 | private String schema_version = "v1"; 22 | 23 | /** 24 | * name_for_human 25 | */ 26 | private String name_for_human ; 27 | 28 | /** 29 | * name_for_model 30 | */ 31 | private String name_for_model; 32 | 33 | /** 34 | * description_for_human 35 | */ 36 | private String description_for_human; 37 | 38 | /** 39 | * description_for_model 40 | */ 41 | private String description_for_model; 42 | 43 | /** 44 | * auth 45 | */ 46 | private Map auth; 47 | 48 | /** 49 | * api 50 | */ 51 | private Map api; 52 | 53 | /** 54 | * headers 55 | */ 56 | private Map headers; 57 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/meta/Protocol.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool.meta; 6 | 7 | import com.alipay.muagent.model.tool.meta.serilizer.JsonObjectDeserializer; 8 | import com.alipay.muagent.model.tool.meta.serilizer.JsonObjectSerializer; 9 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 10 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 11 | import com.google.gson.JsonObject; 12 | import lombok.Data; 13 | 14 | import java.util.List; 15 | 16 | /** 17 | * @author renmao.rm 18 | * @version : Protocol.java, v 0.1 2024年10月11日 上午10:29 renmao.rm Exp $ 19 | */ 20 | @Data 21 | public class Protocol { 22 | 23 | /** 24 | * 请求的方法: 25 | * GET, 26 | * HEAD, 27 | * POST, 28 | * PUT, 29 | * PATCH, 30 | * DELETE, 31 | * OPTIONS, 32 | * TRACE; 33 | * 34 | */ 35 | private String method; 36 | 37 | /** 38 | * 请求路径 39 | */ 40 | private String path; 41 | 42 | /** 43 | * 请求参数 44 | */ 45 | private List parameters; 46 | 47 | /** 48 | * responses 的结构暂时忽略 49 | */ 50 | @JsonSerialize(using = JsonObjectSerializer.class) 51 | @JsonDeserialize(using = JsonObjectDeserializer.class) 52 | private JsonObject responses; 53 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/meta/ProtocolParameter.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool.meta; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : ProtocolParameter.java, v 0.1 2024年10月11日 上午10:35 renmao.rm Exp $ 12 | */ 13 | @Data 14 | public class ProtocolParameter { 15 | 16 | /** 17 | * 参数位置,body/path/query 18 | */ 19 | private String in; 20 | 21 | /** 22 | * schema 23 | */ 24 | private ProtocolSchema schema; 25 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/meta/ProtocolSchema.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool.meta; 6 | 7 | import com.fasterxml.jackson.annotation.JsonProperty; 8 | import lombok.Data; 9 | 10 | /** 11 | * @author renmao.rm 12 | * @version : ProtocolSchema.java, v 0.1 2024年10月11日 上午10:35 renmao.rm Exp $ 13 | */ 14 | @Data 15 | public class ProtocolSchema { 16 | 17 | /** 18 | * $ref,参数的引用 id,与 FieldNode.id 是同一个值,该值将二者关联起来 19 | * 即可以通过 FieldNode.id 找到对应的 schema 参数,进而确定这个参数实际的参数位置 20 | */ 21 | @JsonProperty("$ref") 22 | private String $ref; 23 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/meta/Protocols.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool.meta; 6 | 7 | import com.alipay.muagent.model.tool.meta.serilizer.JsonObjectDeserializer; 8 | import com.alipay.muagent.model.tool.meta.serilizer.JsonObjectSerializer; 9 | import com.fasterxml.jackson.databind.annotation.JsonDeserialize; 10 | import com.fasterxml.jackson.databind.annotation.JsonSerialize; 11 | import com.google.gson.JsonObject; 12 | import lombok.Data; 13 | 14 | /** 15 | * @author renmao.rm 16 | * @version : Protocols.java, v 0.1 2024年10月11日 上午10:25 renmao.rm Exp $ 17 | */ 18 | @Data 19 | public class Protocols { 20 | 21 | /** 22 | * http 23 | */ 24 | private Protocol http; 25 | 26 | /** 27 | * tr 28 | */ 29 | @JsonSerialize(using = JsonObjectSerializer.class) 30 | @JsonDeserialize(using = JsonObjectDeserializer.class) 31 | private JsonObject tr; 32 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/meta/ToolDef.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool.meta; 6 | 7 | import lombok.Data; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : ToolDef.java, v 0.1 2024年10月11日 上午10:46 renmao.rm Exp $ 12 | */ 13 | @Data 14 | public class ToolDef { 15 | 16 | private String name; 17 | 18 | /** 19 | * Tool的详细描述,描述Tool是用来做什么的,描述中包含接受什么样的参数,返回什么什么样的内容 20 | */ 21 | private String description; 22 | 23 | /** 24 | * 入参定义 25 | */ 26 | private ToolDefParam parameters; 27 | 28 | /** 29 | * 结果定义 30 | */ 31 | private ToolDefParam result; 32 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/meta/ToolDefParam.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool.meta; 6 | 7 | import lombok.Data; 8 | 9 | import java.util.Map; 10 | import java.util.Set; 11 | 12 | /** 13 | * @author renmao.rm 14 | * @version : ToolDefParam.java, v 0.1 2024年10月11日 上午10:46 renmao.rm Exp $ 15 | */ 16 | @Data 17 | public class ToolDefParam { 18 | 19 | /** 20 | * 类型枚举值 21 | */ 22 | private String type; 23 | 24 | /** 25 | * 属性描述信息 26 | */ 27 | private String description; 28 | 29 | /** 30 | * 枚举值,后续参数填充的信息只能从里面选择 31 | */ 32 | private Set enums; 33 | 34 | /** 35 | * 当 type = ToolDefParamTypeEnum.object 时需要设置 36 | */ 37 | private Map properties; 38 | 39 | /** 40 | * 当 type = ToolDefParamTypeEnum.array 时需要设置 41 | */ 42 | private ToolDefParam items; 43 | 44 | /** 45 | * 必填参数 46 | */ 47 | private Set required; 48 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/meta/serilizer/JsonObjectDeserializer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool.meta.serilizer; 6 | 7 | import com.fasterxml.jackson.core.JsonParser; 8 | import com.fasterxml.jackson.databind.DeserializationContext; 9 | import com.fasterxml.jackson.databind.JsonDeserializer; 10 | import com.google.gson.JsonObject; 11 | 12 | import java.io.IOException; 13 | 14 | public class JsonObjectDeserializer extends JsonDeserializer { 15 | 16 | @Override 17 | public JsonObject deserialize(JsonParser p, DeserializationContext ctxt) throws IOException { 18 | return com.google.gson.JsonParser.parseString(p.getText()).getAsJsonObject(); 19 | } 20 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/tool/meta/serilizer/JsonObjectSerializer.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.model.tool.meta.serilizer; 6 | 7 | import com.fasterxml.jackson.core.JsonGenerator; 8 | import com.fasterxml.jackson.databind.SerializerProvider; 9 | import com.fasterxml.jackson.databind.ser.std.StdSerializer; 10 | 11 | import com.google.gson.JsonObject; 12 | 13 | import java.io.IOException; 14 | /** 15 | * @author renmao.rm 16 | * @version : JsonObjectSerializer.java, v 0.1 2024年12月12日 15:58 renmao.rm Exp $ 17 | */ 18 | public class JsonObjectSerializer extends StdSerializer { 19 | 20 | public JsonObjectSerializer(Class t) { 21 | super(t); 22 | } 23 | 24 | @Override 25 | public void serialize(JsonObject value, JsonGenerator gen, SerializerProvider provider) throws IOException { 26 | gen.writeRawValue(value.toString()); 27 | } 28 | } -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/trace/TraceContext.java: -------------------------------------------------------------------------------- 1 | package com.alipay.muagent.model.trace; 2 | 3 | import lombok.Data; 4 | 5 | /** 6 | * @author Joshua 7 | * @version TraceContext.java v1.0 2024-11-20 20:21 8 | **/ 9 | @Data 10 | public class TraceContext { 11 | 12 | private String traceId; 13 | 14 | } 15 | -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/trace/TraceThreadLocalContext.java: -------------------------------------------------------------------------------- 1 | package com.alipay.muagent.model.trace; 2 | 3 | import java.util.EmptyStackException; 4 | 5 | /** 6 | * @author Joshua 7 | * @version TraceThreadLocalContext.java v1.0 2024-11-20 20:24 8 | **/ 9 | public class TraceThreadLocalContext { 10 | 11 | private final ThreadLocal traceContextThreadLocal = new ThreadLocal<>(); 12 | 13 | public void push(TraceContext traceContext) { 14 | if (traceContext == null) { 15 | return; 16 | } 17 | traceContextThreadLocal.set(traceContext); 18 | } 19 | 20 | public TraceContext pop() throws EmptyStackException { 21 | if (this.isEmpty()) { 22 | return null; 23 | } 24 | TraceContext traceContext = traceContextThreadLocal.get(); 25 | this.clear(); 26 | return traceContext; 27 | } 28 | 29 | public TraceContext getCurrentTraceContext() throws EmptyStackException { 30 | if (this.isEmpty()) { 31 | return null; 32 | } 33 | return traceContextThreadLocal.get(); 34 | } 35 | 36 | public boolean isEmpty() { 37 | TraceContext traceContext = traceContextThreadLocal.get(); 38 | return traceContext == null; 39 | } 40 | 41 | public void clear() { 42 | traceContextThreadLocal.remove(); 43 | } 44 | } 45 | -------------------------------------------------------------------------------- /runtime/model/src/main/java/com/alipay/muagent/model/trace/TraceThreadLocalContextHolder.java: -------------------------------------------------------------------------------- 1 | package com.alipay.muagent.model.trace; 2 | 3 | /** 4 | * @author Joshua 5 | * @version TraceThreadLocalContextHolder.java v1.0 2024-11-20 20:28 6 | **/ 7 | public class TraceThreadLocalContextHolder { 8 | 9 | /** 10 | * singleton SofaTraceContext 11 | */ 12 | private static final TraceThreadLocalContext SINGLE_TRACE_CONTEXT = new TraceThreadLocalContext(); 13 | 14 | /** 15 | * Get threadlocal trace context 16 | * 17 | * @return TraceThreadLocalContext 18 | */ 19 | public static TraceThreadLocalContext getTraceThreadLocalContext() { 20 | return SINGLE_TRACE_CONTEXT; 21 | } 22 | 23 | } 24 | -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/agent/AgentService.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.service.agent; 6 | 7 | import com.alipay.muagent.model.agent.Agent; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * @author renmao.rm 13 | * @version : AgentService.java, v 0.1 2024年10月11日 下午9:06 renmao.rm Exp $ 14 | */ 15 | public interface AgentService { 16 | 17 | List queryAgentList(); 18 | } -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/agent/impl/AgentServiceImpl.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.service.agent.impl; 6 | 7 | import com.alipay.muagent.model.agent.Agent; 8 | import com.alipay.muagent.service.agent.AgentService; 9 | import com.alipay.muagent.util.GsonUtils; 10 | import com.google.common.collect.Lists; 11 | import org.springframework.stereotype.Service; 12 | 13 | import java.util.List; 14 | 15 | /** 16 | * @author renmao.rm 17 | * @version : AgentServiceImpl.java, v 0.1 2024年10月11日 下午9:16 renmao.rm Exp $ 18 | */ 19 | @Service 20 | public class AgentServiceImpl implements AgentService { 21 | 22 | @Override 23 | public List queryAgentList() { 24 | String agentStr = "{\"id\":\"9400019\",\"aiRecommend\":false,\"agentId\":\"20240905000110000000000455769\",\"agentName\":\"智能画布EKG演示Agent\",\"agentType\":\"PRIVATE\",\"agentDesc\":\"智能画布EKG演示Agent\",\"avatar\":\"http://localhost:8080/avatar/nex.png\",\"buildType\":\"TEMPLATE\",\"buildTypeInfo\":\"SRE_TEMPLATE\",\"source\":\"OPSGPT\",\"agentAttribute\":\"BIZ\",\"pluginStatus\":\"OFF\",\"spaceId\":\"8400002\",\"debugVersion\":null,\"publishVersion\":null,\"lastModifyUser\":\"jikong.tp\",\"creator\":\"jikong.tp\",\"gmtModified\":\"2024-09-05T06:42:37.000+00:00\",\"lastModifyUserView\":\"济空\",\"relationshipList\":null,\"agentRelationshipList\":null,\"knowledgeBaseRelationshipList\":null,\"skillRelationshipList\":null}"; 25 | Agent agent = GsonUtils.fromString(Agent.class, agentStr); 26 | 27 | List agents = Lists.newArrayList(); 28 | agents.add(agent); 29 | return agents; 30 | } 31 | } -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/chat/ChatService.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.service.chat; 6 | 7 | import com.alipay.muagent.model.chat.ChatRequest; 8 | import com.alipay.muagent.model.ekg.EkgQueryRequest; 9 | import com.alipay.muagent.model.ekg.EkgAlgorithmResult; 10 | import org.springframework.web.servlet.mvc.method.annotation.SseEmitter; 11 | 12 | /** 13 | * @author renmao.rm 14 | * @version : ChatService.java, v 0.1 2024年10月09日 上午10:57 renmao.rm Exp $ 15 | */ 16 | public interface ChatService { 17 | 18 | /** 19 | * 流式对话 20 | * 21 | * @param emitter 22 | * @param request 23 | */ 24 | void chat(SseEmitter emitter, ChatRequest request); 25 | 26 | /** 27 | * 提交 ekg 任务 28 | * 29 | * @param request 30 | * @return 31 | */ 32 | EkgAlgorithmResult sendRequestToEkgPlanner(EkgQueryRequest request); 33 | } -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/chat/configuration/EkgConfiguration.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.service.chat.configuration; 6 | 7 | import com.alipay.muagent.model.ekg.configuration.Config; 8 | import com.google.common.collect.Lists; 9 | import org.springframework.beans.factory.annotation.Value; 10 | import org.springframework.context.annotation.Bean; 11 | import org.springframework.context.annotation.Configuration; 12 | 13 | /** 14 | * @author renmao.rm 15 | * @version : EkgConfiguration.java, v 0.1 2024年10月10日 下午9:02 renmao.rm Exp $ 16 | */ 17 | @Configuration 18 | public class EkgConfiguration { 19 | 20 | @Value("${ekg.chat.url}") 21 | private String ekgChatUrl; 22 | 23 | @Value("${ekg.candidate.tools}") 24 | private String ekgCadiDataTools; 25 | 26 | @Bean 27 | public Config getConfig() { 28 | Config config = new Config(); 29 | config.setEkgUrl(ekgChatUrl); 30 | config.setToolKeys(Lists.newArrayList(ekgCadiDataTools.split(","))); 31 | return config; 32 | } 33 | } -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/connector/Connector.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.service.connector; 6 | 7 | import com.alipay.muagent.model.enums.tool.ToolProtocolEnum; 8 | import com.alipay.muagent.model.tool.TaskExeContext; 9 | import com.alipay.muagent.model.tool.ToolExeResponse; 10 | 11 | /** 12 | * @author renmao.rm 13 | * @version : Connector.java, v 0.1 2024年10月10日 下午9:13 renmao.rm Exp $ 14 | */ 15 | public interface Connector { 16 | 17 | ToolExeResponse executeTool(TaskExeContext context); 18 | 19 | ToolProtocolEnum register(); 20 | } -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/connector/ConnectorManager.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.service.connector; 6 | 7 | import com.alipay.muagent.model.enums.tool.ToolProtocolEnum; 8 | import org.springframework.beans.factory.InitializingBean; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Component; 11 | 12 | import java.util.List; 13 | import java.util.Map; 14 | import java.util.stream.Collectors; 15 | 16 | /** 17 | * @author renmao.rm 18 | * @version : ConnectorManager.java, v 0.1 2024年10月10日 下午10:11 renmao.rm Exp $ 19 | */ 20 | @Component 21 | public class ConnectorManager implements InitializingBean { 22 | 23 | @Autowired 24 | private List connectors; 25 | 26 | private static Map p2Connector; 27 | 28 | @Override 29 | public void afterPropertiesSet() throws Exception { 30 | p2Connector = connectors.stream().collect(Collectors.toMap(Connector::register, c -> c)); 31 | } 32 | 33 | public Connector getConnector(ToolProtocolEnum p) { 34 | return p2Connector.get(p); 35 | } 36 | } -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/ekgmanager/EkgGraphStorageClient.java: -------------------------------------------------------------------------------- 1 | /* 2 | * Ant Group 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.service.ekgmanager; 6 | 7 | import com.alipay.muagent.model.ekg.storage.GraphGraph; 8 | import com.alipay.muagent.model.ekg.storage.GraphNode; 9 | import com.alipay.muagent.model.ekg.storage.GraphUpdateRequest; 10 | 11 | import java.util.List; 12 | 13 | /** 14 | * EKG存储client 15 | * 16 | * @author jikong 17 | * @version EkgGraphStorageClient.java, v 0.1 2024年10月11日 19:41 jikong 18 | */ 19 | public interface EkgGraphStorageClient { 20 | /** 21 | * 根据团队ID查询图谱(外层图谱) 22 | * 23 | * @param teamRootId 团队根节点ID 24 | * @return 25 | */ 26 | GraphGraph getGraphByTeam(String teamRootId); 27 | 28 | /** 29 | * 根据节点ID查询图谱(内层图谱) 30 | * 31 | * @param nodeId 节点ID 32 | * @return 图谱(内层图谱) 33 | */ 34 | GraphGraph getGraphByNode(String nodeId, String nodeType); 35 | 36 | /** 37 | * 获取节点详情 38 | * 39 | * @param nodeId 节点ID 40 | * @return 节点详情 41 | */ 42 | GraphNode getNode(String nodeId, String nodeType); 43 | 44 | /** 45 | * 更新图谱数据 46 | * 47 | * @param request 请求参数 48 | * @return 是否更新成功 49 | */ 50 | GraphGraph updateGraph(GraphUpdateRequest request); 51 | 52 | /** 53 | * 节点搜索 54 | * 55 | * @param teamId 团队ID 56 | * @param text 搜索文本 57 | * @return 搜索结果 58 | */ 59 | List searchNode(String teamId, String text); 60 | 61 | /** 62 | * 根据节点ID查询祖先链路 63 | * 64 | * @param teamRootId 团队根节点ID 65 | * @param nodeId 节点ID 66 | * @return 祖先链路 67 | */ 68 | GraphGraph getNodeAncestor(String teamRootId, String nodeId, String nodeType); 69 | } -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/mybatisplus/dto/Converter.java: -------------------------------------------------------------------------------- 1 | package com.alipay.muagent.service.mybatisplus.dto; 2 | 3 | import java.util.function.Function; 4 | 5 | /** 6 | * @author chenjue.wwp 7 | * @version : LocalToolLoader.java, v 0.1 2024年12月10日 下午7:23 chenjue.wwp Exp $ 8 | */ 9 | public class Converter { 10 | 11 | private final Function fromDto; 12 | private final Function fromEntity; 13 | 14 | /** 15 | * @param fromDto entity function 16 | * @param fromEntity domain function 17 | */ 18 | public Converter(final Function fromDto, final Function fromEntity) { 19 | this.fromDto = fromDto; 20 | this.fromEntity = fromEntity; 21 | } 22 | 23 | /** 24 | * @param dto DTO entity 25 | * @return T -> U 26 | */ 27 | public final U convertFromDto(final T dto) { 28 | if (dto == null) { 29 | throw new RuntimeException("dto is null"); 30 | } 31 | return fromDto.apply(dto); 32 | } 33 | 34 | /** 35 | * @param entity domain entity 36 | * @return U -> T 37 | */ 38 | public final T convertFromEntity(final U entity) { 39 | if (entity == null) { 40 | throw new RuntimeException("entity is null"); 41 | } 42 | return fromEntity.apply(entity); 43 | } 44 | 45 | } -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/mybatisplus/dto/ToolDO.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.service.mybatisplus.dto; 6 | 7 | import com.baomidou.mybatisplus.annotation.TableName; 8 | import lombok.Data; 9 | import java.util.Date; 10 | 11 | /** 12 | * @author chenjue.wwp 13 | * @version $Id: ToolDO.java, v 0.1 2024-11-22 14:35 Exp $$ 14 | */ 15 | @Data 16 | @TableName(value = "tool") 17 | public class ToolDO { 18 | private Long id; 19 | 20 | /** 21 | * 创建时间 22 | */ 23 | private Date gmtCreate; 24 | 25 | /** 26 | * 修改时间 27 | */ 28 | private Date gmtModified; 29 | 30 | /** 31 | * tool类型标识,用于区分不同类型的task 32 | */ 33 | private String toolKey; 34 | 35 | /** 36 | * tool的描述 37 | */ 38 | private String description; 39 | 40 | /** 41 | * tool的名称 42 | */ 43 | private String toolName; 44 | 45 | /** 46 | * 创建人 47 | */ 48 | private String operatorCreate; 49 | 50 | /** 51 | * 修改人 52 | */ 53 | private String operatorModified; 54 | 55 | /** 56 | * Tool的版本 57 | */ 58 | private String version; 59 | 60 | /** 61 | * Tool的owner 62 | */ 63 | private String owner; 64 | 65 | /** 66 | * JSON格式存放 67 | */ 68 | private String toolJson; 69 | } -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/mybatisplus/dto/ToolJson.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.service.mybatisplus.dto; 6 | 7 | import com.alipay.muagent.model.enums.tool.ToolProtocolEnum; 8 | import com.alipay.muagent.model.tool.meta.ApiIvkSchema; 9 | import com.alipay.muagent.model.tool.meta.ManifestSchema; 10 | import com.alipay.muagent.model.tool.meta.ToolDef; 11 | import lombok.Data; 12 | 13 | /** 14 | * 对应DB中的tool_json,用来存放tool的复杂属性,不在DB中存放多个字段 15 | * @author chenjue.wwp 16 | * @version $Id: ToolGson.java, v 0.1 2024-11-22 14:38 Exp $$ 17 | */ 18 | @Data 19 | public class ToolJson { 20 | /** 21 | * tool的定义 22 | */ 23 | private ToolDef toolDefinition; 24 | /** 25 | * 用于做request转化的Groovy脚本代码 26 | */ 27 | private String requestGroovy; 28 | 29 | /** 30 | * 用于做response转化的Groovy脚本低吗 31 | */ 32 | private String responseGroovy; 33 | /** 34 | * 描述Tool背后的API或者大模型调用的元数据 35 | */ 36 | private ManifestSchema manifestSchema; 37 | 38 | /** 39 | * Tool使用API的协议类型,SOFA_RPC、HTTP、MAYA、LOCAL 40 | */ 41 | private ToolProtocolEnum toolProtocol; 42 | 43 | /** 44 | * API的schema, Swagger的json格式 45 | */ 46 | private ApiIvkSchema apiSchema; 47 | } -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/mybatisplus/mapper/ToolDoMapper.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.service.mybatisplus.mapper; 6 | 7 | import com.alipay.muagent.service.mybatisplus.dto.ToolDO; 8 | import com.baomidou.mybatisplus.core.mapper.BaseMapper; 9 | 10 | /** 11 | * @author chenjue.wwp 12 | * @version $Id: ToolMapper.java, v 0.1 2024-11-21 20:53 Exp $$ 13 | */ 14 | public interface ToolDoMapper extends BaseMapper { 15 | } -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/sheduler/SchedulerManager.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.service.sheduler; 6 | 7 | import com.alipay.muagent.model.enums.scheduler.TaskSchedulerTypeEnum; 8 | import org.springframework.beans.factory.InitializingBean; 9 | import org.springframework.beans.factory.annotation.Autowired; 10 | import org.springframework.stereotype.Component; 11 | 12 | import java.util.List; 13 | import java.util.Map; 14 | import java.util.stream.Collectors; 15 | 16 | /** 17 | * @author renmao.rm 18 | * @version : SchedulerManager.java, v 0.1 2024年10月11日 下午2:59 renmao.rm Exp $ 19 | */ 20 | @Component 21 | public class SchedulerManager implements InitializingBean { 22 | 23 | @Autowired 24 | private List connectors; 25 | 26 | private static Map p2Connector; 27 | 28 | @Override 29 | public void afterPropertiesSet() throws Exception { 30 | p2Connector = connectors.stream().collect(Collectors.toMap(Scheduler::register, c -> c)); 31 | } 32 | 33 | public Scheduler getScheduler(TaskSchedulerTypeEnum p) { 34 | return p2Connector.get(p); 35 | } 36 | } -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/shell/ShellService.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.service.shell; 6 | 7 | import com.alipay.muagent.model.shell.ShellRequest; 8 | import com.alipay.muagent.model.shell.ShellResponse; 9 | 10 | /** 11 | * @author renmao.rm 12 | * @version : ShellService.java, v 0.1 2024年10月11日 上午10:57 renmao.rm Exp $ 13 | */ 14 | public interface ShellService { 15 | 16 | ShellResponse execute(ShellRequest request); 17 | } -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/thread/ThreadPoolConfig.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.service.thread; 6 | 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; 10 | 11 | /** 12 | * @author renmao.rm 13 | * @version : ThreadPoolConfig.java, v 0.1 2024年10月09日 下午4:52 renmao.rm Exp $ 14 | */ 15 | @Configuration 16 | public class ThreadPoolConfig { 17 | 18 | /** 19 | * 会话线程池 20 | * 21 | * @return the thread pool 22 | */ 23 | @Bean("chatSseEmitterPool") 24 | public ThreadPoolTaskExecutor threadPoolTaskExecutor() { 25 | ThreadPoolTaskExecutor threadPoolTaskExecutor = new ThreadPoolTaskExecutor(); 26 | threadPoolTaskExecutor.setCorePoolSize(10); 27 | threadPoolTaskExecutor.setMaxPoolSize(2000); 28 | threadPoolTaskExecutor.setQueueCapacity(10000); 29 | return threadPoolTaskExecutor; 30 | } 31 | } -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/tool/loader/ToolLoader.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.service.tool.loader; 6 | 7 | import com.alipay.muagent.model.tool.meta.Tool; 8 | 9 | import java.util.List; 10 | 11 | /** 12 | * @author renmao.rm 13 | * @version : ToolLoader.java, v 0.1 2024年10月11日 下午7:22 renmao.rm Exp $ 14 | */ 15 | public interface ToolLoader { 16 | 17 | Tool queryToolById(Long id); 18 | 19 | List queryToolsByIdList(List id); 20 | 21 | Tool queryToolByKey(String toolKey); 22 | 23 | List queryToolsByKeyList(List keys); 24 | } -------------------------------------------------------------------------------- /runtime/service/src/main/java/com/alipay/muagent/service/tool/loader/configuration/LoaderConfiguration.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.service.tool.loader.configuration; 6 | 7 | import org.springframework.context.annotation.Bean; 8 | import org.springframework.context.annotation.Configuration; 9 | import org.springframework.core.io.ResourceLoader; 10 | import org.springframework.core.io.support.PathMatchingResourcePatternResolver; 11 | 12 | /** 13 | * @author renmao.rm 14 | * @version : Configuration.java, v 0.1 2024年10月16日 下午10:05 renmao.rm Exp $ 15 | */ 16 | @Configuration 17 | public class LoaderConfiguration { 18 | 19 | @Bean 20 | public ResourceLoader resourceLoader() { 21 | return new PathMatchingResourcePatternResolver(); 22 | } 23 | } -------------------------------------------------------------------------------- /runtime/web/src/main/java/com/alipay/muagent/web/AgentController.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.web; 6 | 7 | import com.alipay.muagent.model.agent.Agent; 8 | import com.alipay.muagent.service.agent.AgentService; 9 | import com.alipay.muagent.web.base.BaseController; 10 | import com.alipay.muagent.web.model.Result; 11 | import org.springframework.beans.factory.annotation.Autowired; 12 | import org.springframework.web.bind.annotation.RequestMapping; 13 | import org.springframework.web.bind.annotation.RequestMethod; 14 | import org.springframework.web.bind.annotation.ResponseBody; 15 | import org.springframework.web.bind.annotation.RestController; 16 | 17 | import java.util.List; 18 | 19 | /** 20 | * @author renmao.rm 21 | * @version : AgentController.java, v 0.1 2024年10月11日 下午9:00 renmao.rm Exp $ 22 | */ 23 | @RestController 24 | @RequestMapping("/api/portal/agent") 25 | public class AgentController extends BaseController { 26 | 27 | @Autowired 28 | private AgentService agentService; 29 | 30 | @RequestMapping(value = "/queryList", method = RequestMethod.GET) 31 | @ResponseBody 32 | public Result> exeToolTest() { 33 | return executeTemplate(()-> agentService.queryAgentList()); 34 | } 35 | } -------------------------------------------------------------------------------- /runtime/web/src/main/java/com/alipay/muagent/web/TaskController.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.web; 6 | 7 | import com.alipay.muagent.model.scheduler.SubmitTaskRequest; 8 | import com.alipay.muagent.model.scheduler.TaskExeResponse; 9 | import com.alipay.muagent.service.sheduler.Scheduler; 10 | import com.alipay.muagent.service.sheduler.SchedulerManager; 11 | import com.alipay.muagent.web.base.BaseController; 12 | import com.alipay.muagent.web.model.Result; 13 | import org.springframework.beans.factory.annotation.Autowired; 14 | import org.springframework.web.bind.annotation.RequestBody; 15 | import org.springframework.web.bind.annotation.RequestMapping; 16 | import org.springframework.web.bind.annotation.RequestMethod; 17 | import org.springframework.web.bind.annotation.ResponseBody; 18 | import org.springframework.web.bind.annotation.RestController; 19 | 20 | /** 21 | * @author renmao.rm 22 | * @version : TaskController.java, v 0.1 2024年10月12日 下午5:07 renmao.rm Exp $ 23 | */ 24 | @RestController 25 | @RequestMapping("/task") 26 | public class TaskController extends BaseController { 27 | 28 | @Autowired 29 | private SchedulerManager manager; 30 | 31 | @RequestMapping(method = RequestMethod.POST) 32 | @ResponseBody 33 | public Result submitTask(@RequestBody SubmitTaskRequest request) { 34 | return executeTemplate(() -> { 35 | Scheduler scheduler = manager.getScheduler(request.getSchedulerType()); 36 | return scheduler.submitTask(request); 37 | }); 38 | } 39 | } -------------------------------------------------------------------------------- /runtime/web/src/main/java/com/alipay/muagent/web/base/ControllerProcessor.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.web.base; 6 | 7 | import java.io.IOException; 8 | 9 | /** 10 | * @author renmao.rm 11 | * @version : ControllerProcessor.java, v 0.1 2024年10月11日 下午8:58 renmao.rm Exp $ 12 | */ 13 | public interface ControllerProcessor { 14 | 15 | T process() throws IOException; 16 | } -------------------------------------------------------------------------------- /runtime/web/src/main/java/com/alipay/muagent/web/interceptor/WebConfigure.java: -------------------------------------------------------------------------------- 1 | /** 2 | * Alipay.com Inc. 3 | * Copyright (c) 2004-2024 All Rights Reserved. 4 | */ 5 | package com.alipay.muagent.web.interceptor; 6 | 7 | import org.springframework.context.annotation.Configuration; 8 | import org.springframework.web.servlet.config.annotation.CorsRegistry; 9 | import org.springframework.web.servlet.config.annotation.WebMvcConfigurer; 10 | 11 | /** 12 | * @author renmao.rm 13 | * @version : WebConfigure.java, v 0.1 2024年10月29日 16:44 renmao.rm Exp $ 14 | */ 15 | @Configuration 16 | public class WebConfigure implements WebMvcConfigurer { 17 | 18 | @Override 19 | public void addCorsMappings(CorsRegistry registry) { 20 | 21 | registry.addMapping("/**") 22 | .allowedOrigins("http://localhost:8000") 23 | .allowedMethods("GET","HEAD","PUT","POST","PATCH","DELETE","OPTIONS") 24 | .allowedHeaders("*") 25 | .allowCredentials(true); 26 | } 27 | } -------------------------------------------------------------------------------- /runtime/web/src/main/resources/spring/spring.xml: -------------------------------------------------------------------------------- 1 | 2 | 9 | 10 | 11 | -------------------------------------------------------------------------------- /setup.py: -------------------------------------------------------------------------------- 1 | import setuptools 2 | 3 | # with open("README.md", "r", encoding="utf-8") as fh: 4 | # long_description = fh.read() 5 | 6 | setuptools.setup( 7 | name="codefuse-muagent", 8 | version="0.1.1", 9 | author="shanshi", 10 | author_email="wyp311395@antgroup.com", 11 | description="An Innovative Agent Framework Driven by KG Engine", 12 | # long_description=long_description, 13 | long_description_content_type="text/markdown", 14 | url="https://github.com/codefuse-ai/CodeFuse-muAgent", 15 | packages=setuptools.find_packages(), 16 | classifiers=[ 17 | "Programming Language :: Python :: 3.9", 18 | "License :: OSI Approved :: Apache Software License", 19 | "Operating System :: OS Independent", 20 | ], 21 | install_requires=[ 22 | "openai==1.34.0", 23 | "langchain==0.2.3", 24 | "langchain_community==0.2.4", 25 | "langchain_openai==0.1.8", 26 | "langchain_huggingface==0.0.3", 27 | "sentence_transformers", 28 | "loguru", 29 | "fastapi", 30 | "pandas", 31 | "Pyarrow", 32 | "jieba", 33 | "psutil", 34 | "faiss-cpu", 35 | "notebook", 36 | "docker", 37 | "sseclient", 38 | "edit_distance", 39 | "urllib3==1.26.6", 40 | "ollama", 41 | "colorama", 42 | "pycryptodome", 43 | "dashscope", 44 | # 45 | "chromadb==0.4.17", 46 | "javalang==0.13.0", 47 | "nebula3-python==3.8.2", 48 | "SQLAlchemy==2.0.19", 49 | "redis==5.0.1", 50 | "pydantic<=1.10.14", 51 | "aliyun-log-python-sdk==0.9.0" 52 | ], 53 | ) -------------------------------------------------------------------------------- /tests/agents/react_agent_test.py: -------------------------------------------------------------------------------- 1 | import os, sys 2 | from loguru import logger 3 | import json 4 | 5 | os.environ["do_create_dir"] = "1" 6 | 7 | try: 8 | src_dir = os.path.join( 9 | os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 10 | ) 11 | sys.path.append(src_dir) 12 | import test_config 13 | except Exception as e: 14 | # set your config 15 | logger.error(f"{e}") 16 | 17 | # test local code 18 | src_dir = os.path.join( 19 | os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 20 | ) 21 | sys.path.append(src_dir) 22 | 23 | from muagent.tools import TOOL_SETS 24 | from muagent.schemas import Message 25 | from muagent.agents import BaseAgent 26 | from muagent import get_project_config_from_env 27 | 28 | # log-level,print prompt和llm predict 29 | os.environ["log_verbose"] = "0" 30 | 31 | tools = list(TOOL_SETS) 32 | tools = ["KSigmaDetector", "MetricsQuery"] 33 | role_prompt = "you are a helpful assistant!" 34 | 35 | AGENT_CONFIGS = { 36 | "reacter": { 37 | "system_prompt": role_prompt, 38 | "agent_type": "ReactAgent", 39 | "agent_name": "reacter", 40 | "tools": tools, 41 | "llm_config_name": "qwen_chat" 42 | } 43 | } 44 | os.environ["AGENT_CONFIGS"] = json.dumps(AGENT_CONFIGS) 45 | 46 | # 47 | project_config = get_project_config_from_env() 48 | agent = BaseAgent.init_from_project_config( 49 | "reacter", project_config 50 | ) 51 | 52 | query_content = "帮我确认下127.0.0.1这个服务器的在10点是否存在异常,请帮我判断一下" 53 | query = Message( 54 | role_name="human", 55 | role_type="user", 56 | content=query_content, 57 | ) 58 | # agent.pre_print(query) 59 | output_message = agent.step(query) 60 | print("### intput ###\n", output_message.input_text) 61 | print("### content ###\n", output_message.content) 62 | print("### step content ###\n", output_message.step_content) -------------------------------------------------------------------------------- /tests/db_handler/redis_test.py: -------------------------------------------------------------------------------- 1 | import redis 2 | 3 | # 连接到Redis 4 | client = redis.Redis(host='redis-stack', port=6379) 5 | 6 | # print('host:', '172.18.0.3') 7 | # 检查连接是否成功 8 | try: 9 | pong = client.ping() 10 | if pong: 11 | print("Connected to Redis") 12 | else: 13 | print("Failed to connect to Redis") 14 | except redis.ConnectionError as e: 15 | print(f"Connection error: {e}") 16 | 17 | 18 | 19 | # from nebula3.gclient.net import ConnectionPool 20 | # from nebula3.Config import Config 21 | 22 | # from loguru import logger 23 | 24 | # # 配置 25 | # config = Config() 26 | # config.max_connection_pool_size = 10 27 | 28 | # # 初始化连接池 29 | # connection_pool = ConnectionPool() 30 | 31 | 32 | # # 连接到NebulaGraph,假设NebulaGraph服务运行在本地 33 | 34 | # connection_pool.init([('127.0.0.1', 9669)], config) 35 | 36 | # # 创建会话 37 | # username = 'root' 38 | # password = 'nebula' 39 | # session = connection_pool.get_session(username, password) -------------------------------------------------------------------------------- /tests/db_handler/tbase_handler_test.py: -------------------------------------------------------------------------------- 1 | import time 2 | 3 | from tqdm import tqdm 4 | from loguru import logger 5 | 6 | import sys, os 7 | 8 | src_dir = os.path.join( 9 | os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 10 | ) 11 | print(src_dir) 12 | 13 | sys.path.append(src_dir) 14 | 15 | 16 | print("os.getcwd(): ", os.getcwd()) 17 | 18 | # import muagent 19 | # from muagent import db_handler 20 | 21 | # from muagent.dbhandler.vectordbhandler import tbase_handler 22 | from muagent.db_handler.graph_db_handler.base_gb_handler import GBHandler 23 | # from muagent.db_handler.graph_db_handler.networkx_handler import NetworkxHandler 24 | # from muagent.db_handler.graph_db_handler.geabase_handler import GeaBaseHandler 25 | # from muagent.db_handler.graph_db_handler.aliyun_sls_hanlder import AliYunSLSHandler 26 | # from muagent.db_handler.graph_db_handler.nebula_handler import NebulaHandler 27 | 28 | -------------------------------------------------------------------------------- /tests/httpapis/docker_test.py: -------------------------------------------------------------------------------- 1 | 2 | import docker, sys, os, time, requests, psutil 3 | import subprocess 4 | from docker.types import Mount, DeviceRequest 5 | 6 | import platform 7 | system_name = platform.system() 8 | USE_TTY = system_name in ["Windows"] 9 | 10 | 11 | client = docker.from_env() 12 | 13 | mount = Mount( 14 | type='bind', 15 | source="/d/project/gitlab/ant_code/muagent", 16 | target='/home/user/muagent', 17 | read_only=False # 如果需要只读访问,将此选项设置为True 18 | ) 19 | 20 | ports={ 21 | f"8080/tcp": f"8888/tcp", 22 | f"3737/tcp": f"3737/tcp", 23 | } 24 | 25 | 26 | print( client.networks.list()) 27 | 28 | network_name ='my_network' 29 | networks = client.networks.list() 30 | if any([network_name==i.attrs["Name"] for i in networks]): 31 | network = client.networks.get(network_name) 32 | else: 33 | network = client.networks.create('my_network', driver='bridge') 34 | container = client.containers.run( 35 | image="muagent:test", 36 | command="bash", 37 | mounts=[mount], 38 | name="test", 39 | mem_limit="8g", 40 | # device_requests=[DeviceRequest(count=-1, capabilities=[['gpu']])], 41 | # network_mode="host", 42 | ports=ports, 43 | stdin_open=True, 44 | detach=True, 45 | tty=USE_TTY, 46 | network='my_network', 47 | ) 48 | 49 | -------------------------------------------------------------------------------- /tests/httpapis/fastapi_connect_test.py: -------------------------------------------------------------------------------- 1 | # 导入必要的库 2 | import requests 3 | import json 4 | 5 | #from muagent.schemas.apis.ekg_api_schema import * 6 | 7 | # 定义 API 基本 URL 8 | base_url = "http://localhost:3737" 9 | 10 | # 测试获取嵌入模型参数 11 | response = requests.get(f"{base_url}/embeddings/params") 12 | print(response.json()) 13 | 14 | -------------------------------------------------------------------------------- /tests/httpapis/fastapi_connet_test_llm.py: -------------------------------------------------------------------------------- 1 | # -*- coding: utf-8 -*- 2 | 3 | 4 | 5 | # 导入必要的库 6 | import requests 7 | import json 8 | 9 | #from muagent.schemas.apis.ekg_api_schema import * 10 | 11 | # 定义 API 基本 URL 12 | base_url = "http://localhost:3737" 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | # #谁是卧底 定制 22 | # request = \ 23 | # { 24 | # "features": { 25 | # "query": { 26 | # "observation": "{\"content\":\"开始游戏\"}", 27 | # "scene": "UNDERCOVER", 28 | # "sessionId": "41faeed1_39ba_414b_dcad_f22e7b32caae006" 29 | # } 30 | # } 31 | # } 32 | 33 | 34 | # #谁是卧底 通用 35 | # request = \ 36 | # { 37 | # "features": { 38 | # "query": { 39 | # "scene": "NEXA", 40 | # "startRootNodeId": '4bf08f20487bfb3d34048ddf455bf5dd', #hash_id('剧本杀' ), 41 | # "intentionRule": ["nlp"], 42 | # "intentionData": "执行谁是卧底进程", 43 | # "observation": "{\"content\":\"开始游戏\"}", 44 | # "sessionId": "41faeed1_39ba_414b_dcad_f22e7b32caae003" 45 | # } 46 | # } 47 | # } 48 | 49 | #llm 调用 50 | request = \ 51 | { 52 | "text": "你是谁?", 53 | "stop":"aaa" 54 | } 55 | 56 | 57 | # 测试获取嵌入模型参数 58 | response = requests.post(f"{base_url}/llm/generate", json = request) 59 | print(response.json()) 60 | print(response) 61 | 62 | 63 | -------------------------------------------------------------------------------- /tests/httpapis/fastapi_test.py: -------------------------------------------------------------------------------- 1 | from fastapi import FastAPI 2 | import asyncio 3 | import uvicorn 4 | import time 5 | 6 | from pydantic import BaseModel 7 | 8 | 9 | app = FastAPI() 10 | 11 | # get node by nodeid and nodetype 12 | class GetNodeRequest(BaseModel): 13 | nodeid: str 14 | nodeType: str 15 | 16 | 17 | # get node by nodeid and nodetype 18 | class GetNodeResponse(BaseModel): 19 | test: str 20 | 21 | 22 | # ~/ekg/node/search 23 | @app.get("/ekg/node", response_model=GetNodeResponse) 24 | def get_node(request: GetNodeRequest): 25 | # 添加预测逻辑的代码 26 | print(request) 27 | return GetNodeResponse( 28 | test="test" 29 | ) 30 | # 一个异步路由 31 | @app.get("/") 32 | async def read_root(): 33 | await asyncio.sleep(1) # 模拟一个异步操作 34 | return {"message": "Hello, World!"} 35 | 36 | # 另一个异步路由 37 | @app.get("/items/{item_id}") 38 | async def read_item(item_id: int, q: str = None): 39 | await asyncio.sleep(5) # 模拟延迟 40 | return {"item_id": item_id, "q": q} 41 | 42 | # 另一个异步路由 43 | @app.get("/itemstest/{item_id}") 44 | def read_item(item_id: int, q: str = None): 45 | time.sleep(5) # 模拟延迟 46 | return {"item_id": item_id, "q": q} 47 | 48 | 49 | # 均能并发触发,好像对于io操作会默认管理 50 | uvicorn.run(app, host="127.0.0.1", port=3737) 51 | -------------------------------------------------------------------------------- /tests/llm_models/embedding_test.py: -------------------------------------------------------------------------------- 1 | from loguru import logger 2 | import os, sys 3 | src_dir = os.path.join( 4 | os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 5 | ) 6 | sys.path.append(src_dir) 7 | try: 8 | import test_config 9 | api_key = os.environ["OPENAI_API_KEY"] 10 | api_base_url= os.environ["API_BASE_URL"] 11 | model_name = os.environ["model_name"] 12 | embed_model = os.environ["embed_model"] 13 | embed_model_path = os.environ["embed_model_path"] 14 | except Exception as e: 15 | # set your config 16 | api_key = "" 17 | api_base_url= "" 18 | model_name = "" 19 | embed_model = "" 20 | embed_model_path = "" 21 | logger.error(f"{e}") 22 | 23 | 24 | src_dir = os.path.join( 25 | os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 26 | ) 27 | sys.path.append(src_dir) 28 | 29 | from muagent.models import get_model 30 | from muagent.schemas.models import ModelConfig 31 | import json 32 | 33 | model_configs = json.loads(os.environ["MODEL_CONFIGS"]) 34 | 35 | for model_type in model_configs.keys(): 36 | if "_embedding" not in model_type: continue 37 | model_config = model_configs[model_type] 38 | embed_config = ModelConfig( 39 | config_name="model_test", 40 | model_type=model_type, 41 | model_name=model_config["model_name"], 42 | api_key=model_config["api_key"], 43 | ) 44 | 45 | model = get_model(embed_config) 46 | 47 | 48 | print(model_type, model_config["model_name"], len(model.embed_query("hello"))) -------------------------------------------------------------------------------- /tests/llm_models/openai_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | from loguru import logger 3 | 4 | try: 5 | import os, sys 6 | src_dir = os.path.join( 7 | os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 8 | ) 9 | sys.path.append(src_dir) 10 | import test_config 11 | api_key = os.environ["OPENAI_API_KEY"] 12 | api_base_url= os.environ["API_BASE_URL"] 13 | model_name = os.environ["model_name"] 14 | embed_model = os.environ["embed_model"] 15 | embed_model_path = os.environ["embed_model_path"] 16 | except Exception as e: 17 | # set your config 18 | api_key = "" 19 | api_base_url= "" 20 | model_name = "" 21 | embed_model = "" 22 | embed_model_path = "" 23 | logger.error(f"{e}") 24 | 25 | 26 | 27 | # test 1 28 | from langchain_openai import ChatOpenAI 29 | from langchain.prompts.chat import ChatPromptTemplate 30 | model = ChatOpenAI( 31 | streaming=True, 32 | verbose=True, 33 | openai_api_key=api_key, 34 | openai_api_base=api_base_url, 35 | model_name=model_name, 36 | stop="123" 37 | ) 38 | # test 1 39 | print(model.predict("please output 123!")) 40 | 41 | 42 | # # test 2 43 | # from openai import OpenAI 44 | # http_client = None 45 | # client = OpenAI(api_key=os.environ.get("api_key"), http_client=http_client) 46 | # model = 'gpt-3.5-turbo' 47 | # messages=[{'role': 'user', 'content': 'Hello World'}] 48 | # result = client.chat.completions.create(model=model, messages=messages) 49 | # print(result) 50 | -------------------------------------------------------------------------------- /tests/orm/table_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | from loguru import logger 3 | os.environ["do_create_dir"] = "1" 4 | 5 | # from muagent.orm import create_tables 6 | from muagent.db_handler import create_tables 7 | 8 | 9 | # use to test, don't create some directory 10 | create_tables() -------------------------------------------------------------------------------- /tests/retrieval/text.txt: -------------------------------------------------------------------------------- 1 | 2 | 3 | ## 注意 4 | 注意:整体内容未完善,后续还会完善flow和其它Agent的图例 5 | 6 | ## 核心Connector介绍 7 | 为了便于大家理解整个 MuAgent 的链路,我们采取 Flow 的形式来详细介绍如何通过配置构建 8 | 9 |
10 | 图片 11 |
12 | 13 | 14 |
下面,我们先介绍相关的核心组件
15 | 16 | ### Agent 17 | 在Agent设计层面,我们提供了四种基本的Agent类型,对这些Agent进行Role的基础设定,可满足多种通用场景的交互和使用 18 | 1. BaseAgent:提供基础问答、工具使用、代码执行的功能,根据Prompt格式实现 输入 => 输出 19 | 20 |
21 | 图片 22 |
23 | 24 | 2. ExecutorAgent:对任务清单进行顺序执行,根据 User 或 上一个Agent编排的计划,完成相关任务 25 | 3. ReactAgent:提供标准React的功能,根据问题实现当前任务 26 | 4. SelectorAgent:提供选择Agent的功能,根据User 或 上一个 Agent的问题选择合适的Agent来进行回答. 27 | 28 | 输出后将 message push 到 memory pool 之中,后续通过Memory Manager进行管理 29 | 30 | ### Chain 31 | 基础链路:BaseChain,串联agent的交互,完成相关message和memory的管理 32 | 33 | ### Phase 34 | 基础场景:BasePhase,串联chain的交互,完成相关message和memory的管理 35 | 36 | ### Prompt Manager 37 | Mutli-Agent链路中每一个agent的prompt创建 38 | - 通过对promtp_input_keys和promtp_output_keys对的简单设定,可以沿用预设 Prompt Context 创建逻辑,从而实现agent prompt快速配置 39 | - 也可以对prompt manager模块进行新的 key-context 设计,实现个性化的 Agent Prompt 40 | 41 | ### Memory Manager 42 | 主要用于 chat history 的管理,暂未完成 43 | - 将chat history在数据库进行读写管理,包括user input、 llm output、doc retrieval、code retrieval、search retrieval 44 | - 对 chat history 进行关键信息总结 summary context,作为 prompt context 45 | - 提供检索功能,检索 chat history 或者 summary context 中与问题相关信息,辅助问答 46 | -------------------------------------------------------------------------------- /tests/retrieval/text_splitter_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | from muagent.retrieval.text_splitter import LCTextSplitter 3 | 4 | 5 | 6 | cur_dir = os.path.dirname(os.path.abspath(__file__)) 7 | filepath = os.path.join(cur_dir, "text.txt") 8 | lc_textSplitter = LCTextSplitter(filepath) 9 | docs = lc_textSplitter.file2text() 10 | 11 | print(docs[0]) -------------------------------------------------------------------------------- /tests/sandbox/sandbox_test.py: -------------------------------------------------------------------------------- 1 | from loguru import logger 2 | from muagent.sandbox.pycodebox import PyCodeBox 3 | 4 | 5 | # 测试1 6 | pycodebox = PyCodeBox(remote_url="http://localhost:5050", 7 | remote_ip="http://localhost", 8 | remote_port="5050", 9 | token="mytoken", 10 | do_code_exe=True, 11 | do_remote=False, 12 | do_check_net=False 13 | ) 14 | 15 | 16 | reuslt = pycodebox.chat("```import os\nos.getcwd()```", do_code_exe=True) 17 | print(reuslt) 18 | 19 | # reuslt = pycodebox.chat("```print('hello world!')```", do_code_exe=True) 20 | reuslt = pycodebox.chat("print('hello world!')", do_code_exe=True) 21 | print(reuslt) 22 | 23 | 24 | # # 测试2 25 | # with PyCodeBox(remote_url="http://localhost:5050", 26 | # remote_ip="http://localhost", 27 | # remote_port="5050", 28 | # token="mytoken", 29 | # do_code_exe=True, 30 | # do_remote=False) as codebox: 31 | 32 | # result = codebox.run("'hello world!'") 33 | # print(result) -------------------------------------------------------------------------------- /tests/tools/get_tool.py: -------------------------------------------------------------------------------- 1 | import os 2 | from loguru import logger 3 | 4 | try: 5 | import os, sys 6 | src_dir = os.path.join( 7 | os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 8 | ) 9 | sys.path.append(src_dir) 10 | import test_config 11 | except Exception as e: 12 | # set your config 13 | logger.error(f"{e}") 14 | 15 | 16 | src_dir = os.path.join( 17 | os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) 18 | ) 19 | sys.path.append(src_dir) 20 | 21 | from muagent import get_tool 22 | from muagent.tools import toLangchainTools 23 | 24 | 25 | tools = toLangchainTools([get_tool("Multiplier")]) 26 | 27 | print(get_tool("Multiplier").intput_to_json_schema()) 28 | print(get_tool("Multiplier").output_to_json_schema()) 29 | # tool run 测试 30 | print(tools[0].func(1,2)) -------------------------------------------------------------------------------- /tests/tools/search_test.py: -------------------------------------------------------------------------------- 1 | from duckduckgo_search import DDGS 2 | 3 | with DDGS(proxies="socks5h://127.0.0.1:13659", timeout=20) as ddgs: 4 | ddgs._session.headers["Referer"] = "" 5 | for r in ddgs.text("马克龙、冯德莱恩访华"): 6 | print(r) 7 | -------------------------------------------------------------------------------- /tests/tools/tool_test.py: -------------------------------------------------------------------------------- 1 | import os 2 | from loguru import logger 3 | 4 | try: 5 | import os, sys 6 | src_dir = os.path.join( 7 | os.path.dirname(os.path.dirname(os.path.abspath(__file__))) 8 | ) 9 | sys.path.append(src_dir) 10 | import test_config 11 | api_key = os.environ["OPENAI_API_KEY"] 12 | api_base_url= os.environ["API_BASE_URL"] 13 | model_name = os.environ["model_name"] 14 | embed_model = os.environ["embed_model"] 15 | embed_model_path = os.environ["embed_model_path"] 16 | except Exception as e: 17 | # set your config 18 | api_key = "" 19 | api_base_url= "" 20 | model_name = "" 21 | embed_model = "" 22 | embed_model_path = "" 23 | logger.error(f"{e}") 24 | 25 | 26 | from langchain.tools import StructuredTool 27 | from muagent.tools import ( 28 | WeatherInfo, Multiplier, toLangchainTools, 29 | TOOL_DICT, TOOL_SETS 30 | ) 31 | 32 | # 函数执行 33 | tools = [ 34 | StructuredTool( 35 | name=Multiplier.name, 36 | func=Multiplier.run, 37 | description=Multiplier.description, 38 | args_schema=Multiplier.ToolInputArgs, 39 | ), 40 | StructuredTool( 41 | name=WeatherInfo.name, 42 | func=WeatherInfo.run, 43 | description=WeatherInfo.description, 44 | args_schema=WeatherInfo.ToolInputArgs, 45 | ) 46 | ] 47 | 48 | tools = toLangchainTools([TOOL_DICT["Multiplier"]]) 49 | 50 | # tool run 测试 51 | print(tools[0].func(1,2)) -------------------------------------------------------------------------------- /tests/torch_test.py: -------------------------------------------------------------------------------- 1 | import torch 2 | print(torch.__version__) 3 | print(torch.cuda.is_available()) --------------------------------------------------------------------------------