同步完整源码 - 2026-05-25

This commit is contained in:
xiaoxue
2026-05-25 01:45:00 +08:00
commit 2417bb427c
3151 changed files with 149175 additions and 0 deletions
+8
View File
@@ -0,0 +1,8 @@
blank_issues_enabled: true
contact_links:
- name: 📜 agentUniverse Docs | agentUniverse官方文档
url: https://github.com/antgroup/agentUniverse/blob/master/docs/guidebook/en/Contents.md
about: The docs contains detailed info about the agentUniverse's design concepts, examples, guides, and more.
- name: 👀 agentUniverse Discussions | agentUniverse讨论
url: https://github.com/antgroup/agentUniverse/discussions
about: More topics related to the LLM, AI or Agent can be discussed here.
@@ -0,0 +1,50 @@
name: 🐞 Bug Report | Bug 提交
description: Please describe the bug you found. | 请描述您在使用过程中遇到的问题。
title: "🐞 [Bug] <your title xxx>"
labels: ["bug"]
body:
- type: markdown
attributes:
value: "Please fill out the info before you submit a bug. | 请在您提交 bug 之前,回答以下这些问题。"
- type: textarea
attributes:
label: Version
description: What is the version of your agentUniverse? | 您使用的agentUniverse版本是多少?
placeholder: "Example: version 0.0.15"
validations:
required: true
- type: textarea
attributes:
label: System
description: What is your system environment? | 您的系统版本是什么? [Linux/Mac/Windows]
placeholder: "Example: Ubuntu 20.04"
validations:
required: true
- type: textarea
attributes:
label: Actions
description: What did you do? | 您做了什么操作?
placeholder: "Describe the actions you took"
validations:
required: false
- type: textarea
attributes:
label: Problem
description: What kind of problem are you having? | 您遇到了什么问题?
placeholder: "Describe the problem"
validations:
required: false
- type: textarea
attributes:
label: Expected
description: What is your expected outcome? | 您期望的结果是怎样的?
placeholder: "Describe the expected results"
validations:
required: false
- type: textarea
attributes:
label: reproduce
description: Steps to reproduce the bug | bug复现步骤
placeholder: "Step 1: ..., Step 2: ..."
validations:
required: false
@@ -0,0 +1,15 @@
name: 🙋 Feature Request | 功能请求
description: Please describe the features you expect. | 请描述您期望添加的功能。
title: "🙋 [Feature] <your feature request xxx>"
labels: ["feature"]
body:
- type: markdown
attributes:
value: "Please fill out the info before you submit the feature request.. | 请在功能请求提交以前回答以下这些问题。"
- type: textarea
attributes:
label: feature
description: Please describe in detail the new features you expect. | 请详细描述您预期的新功能
placeholder: "I hope ..."
validations:
required: true
@@ -0,0 +1,63 @@
name: 💡 Question Report | 问题交流
description: Any questions you would like to discuss | 任何您想讨论的话题。
title: "💡 [Question] <your question xxx>"
labels: ["question"]
body:
- type: markdown
attributes:
value: "Please check whether there are any [issues](https://github.com/antgroup/agentUniverse/issues) or [documents](https://github.com/antgroup/agentUniverse/tree/master/docs/guidebook/en) that address your questions. | 搜索是否有[issues](https://github.com/antgroup/agentUniverse/issues) 或[文档](https://github.com/antgroup/agentUniverse/tree/master/docs/guidebook/zh) 提到了您的提问。"
- type: markdown
attributes:
value: "Please fill out the info before you submit a question | 请在您提交问题之前,填写以下信息。"
- type: textarea
attributes:
label: question
description: Please describe in detail the question you would like to discuss. | 请详细描述您想讨论的问题
placeholder: "My question is ..."
validations:
required: true
- type: markdown
attributes:
value: "If it involves the code, you can provide additional information as needed below. | 如果涉及agentUniverse代码您可以按需要补充如下信息。"
- type: textarea
attributes:
label: Version
description: What is the version of your agentUniverse? | 您使用的agentUniverse版本是多少?
placeholder: "Example: version 0.0.15"
validations:
required: false
- type: textarea
attributes:
label: System
description: What is your system environment? | 您的系统版本是什么? [Linux/Mac/Windows]
placeholder: "Example: Ubuntu 20.04"
validations:
required: false
- type: textarea
attributes:
label: Actions
description: What did you do? | 您做了什么操作?
placeholder: "Describe the actions you took"
validations:
required: false
- type: textarea
attributes:
label: Problem
description: What kind of problem are you having? | 您遇到了什么问题?
placeholder: "Describe the problem"
validations:
required: false
- type: textarea
attributes:
label: Expected
description: What is your expected outcome? | 您期望的结果是怎样的?
placeholder: "Describe the expected results"
validations:
required: false
- type: textarea
attributes:
label: reproduce
description: Steps to reproduce the bug | bug复现步骤
placeholder: "Step 1: ..., Step 2: ..."
validations:
required: false
+23
View File
@@ -0,0 +1,23 @@
**When submitting a PR, please confirm the following points and put [x] in the boxes one by one.** | **在提出pr时,请确认了以下几点,并逐一使用[x]符号确认勾选。**
**Checklist | 检查项**
- [x] I have read and understood the [contributor guidelines](https://github.com/antgroup/agentUniverse/blob/master/CONTRIBUTING.md). | 我已阅读并理解[贡献者指南](https://github.com/antgroup/agentUniverse/blob/master/CONTRIBUTING_zh.md) 。
- [x] I have checked for any duplicate features related to this request and communicated with the project maintainers. | 我已检查没有与此请求重复的功能并与项目维护者进行了沟通。
- [x] I accept the suggestion of the maintainers to make changes to or close this PR. | 我接受此PR配合维护人员的建议进行修改或关闭。
- [ ] I have submitted the test files and can provide screenshots of the test results (required for feature or bug fixes) | 我已经提交了测试文件并可提供测试结果截图(功能修改、BUG修复类PR必须提供,其他按需)
- [ ] I have added or modified the documentation related to this PR | 我已经添加或修改了本次pr对应的文档说明(非必要,根据实际PR内容按需添加)
- [ ] I have added examples and notes if needed | 我已经添加了使用案例代码与文档说明(非必要,根据实际PR内容按需添加)
**Please fill in the specific details of this PR:** | **请详细填写本次PR的内容:**
-
-
-
**Please provide the path of test files and submit screenshots or files of the test results(fill in as needed):** | **请填写测试文件路径并提供测试结果截图或文件(按需填写):**
-
**Please list the names of the docs that were added or modified in this PR (fill in as needed):** | **请列出本次PR新增或修改的文档名称(按需填写):**
-
+176
View File
@@ -0,0 +1,176 @@
docs/source
# From https://raw.githubusercontent.com/github/gitignore/main/Python.gitignore
Byte-compiled / optimized / DLL files
*.py[cod]
*$py.class
# C extensions
*.so
# Distribution / packaging
.Python
build/
develop-eggs/
dist/
downloads/
eggs/
.eggs/
lib/
lib64/
parts/
sdist/
var/
wheels/
share/python-wheels/
*.egg-info/
.installed.cfg
*.egg
MANIFEST
# PyInstaller
# Usually these files are written by a python script from a template
# before PyInstaller builds the exe, so as to inject date/other infos into it.
*.manifest
*.spec
# Installer logs
pip-log.txt
pip-delete-this-directory.txt
# Unit test / coverage reports
htmlcov/
.tox/
.nox/
.coverage
.coverage.*
.cache
nosetests.xml
coverage.xml
*.cover
*.py,cover
.hypothesis/
.pytest_cache/
cover/
# Translations
*.mo
*.pot
# Django stuff:
*.log
local_settings.py
db.sqlite3
db.sqlite3-journal
# Flask stuff:
instance/
.webassets-cache
# Scrapy stuff:
.scrapy
# Sphinx documentation
docs/_build/
# PyBuilder
.pybuilder/
target/
# Jupyter Notebook
.ipynb_checkpoints
# IPython
profile_default/
ipython_config.py
# pyenv
# For a library or package, you might want to ignore these files since the code is
# intended to run in multiple environments; otherwise, check them in:
# .python-version
# pipenv
# According to pypa/pipenv#598, it is recommended to include Pipfile.lock in version control.
# However, in case of collaboration, if having platform-specific dependencies or dependencies
# having no cross-platform support, pipenv may install dependencies that don't work, or not
# install all needed dependencies.
#Pipfile.lock
# poetry
# Similar to Pipfile.lock, it is generally recommended to include poetry.lock in version control.
# This is especially recommended for binary packages to ensure reproducibility, and is more
# commonly ignored for libraries.
# https://python-poetry.org/docs/basic-usage/#commit-your-poetrylock-file-to-version-control
poetry.lock
# pdm
# Similar to Pipfile.lock, it is generally recommended to include pdm.lock in version control.
#pdm.lock
# pdm stores project-wide configurations in .pdm.toml, but it is recommended to not include it
# in version control.
# https://pdm.fming.dev/#use-with-ide
.pdm.toml
# PEP 582; used by e.g. github.com/David-OConnor/pyflow and github.com/pdm-project/pdm
__pypackages__/
# Celery stuff
celerybeat-schedule
celerybeat.pid
# SageMath parsed files
*.sage.py
# Environments
.env
.venv
env/
venv/
ENV/
env.bak/
venv.bak/
# Spyder project settings
.spyderproject
.spyproject
# Rope project settings
.ropeproject
# mkdocs documentation
/site
# mypy
.mypy_cache/
.dmypy.json
dmypy.json
# Pyre type checker
.pyre/
# pytype static type analyzer
.pytype/
# Cython debug symbols
cython_debug/
# PyCharm
# JetBrains specific template is maintained in a separate JetBrains.gitignore that can
# be found at https://github.com/github/gitignore/blob/main/Global/JetBrains.gitignore
# and can be added to the global gitignore or merged into this file. For a more nuclear
# option (not recommended) you can uncomment the following to ignore the entire idea folder.
.idea/
.DS_Store
*.sqlite3
*.db
*.pyc
__pycache__/
/poetry.lock
# vscode
.vscode/launch.json
.vscode/
+26
View File
@@ -0,0 +1,26 @@
repos:
# Basic file checks
- repo: https://github.com/pre-commit/pre-commit-hooks
rev: v4.5.0
hooks:
- id: trailing-whitespace
- id: end-of-file-fixer
- id: check-yaml
- id: check-added-large-files
- id: check-merge-conflict
- id: debug-statements
# Python code formatting
- repo: https://github.com/psf/black
rev: 24.10.0
hooks:
- id: black
args: [--line-length=120]
# Python linting with ruff (simplified)
- repo: https://github.com/astral-sh/ruff-pre-commit
rev: v0.8.4
hooks:
- id: ruff
args: [--fix, --exit-non-zero-on-fix]
- id: ruff-format
+344
View File
@@ -0,0 +1,344 @@
# Changelog
**************************************
Language Version: [简体中文](CHANGELOG_zh.md) | [English](CHANGELOG.md)
This document records the version update history of the project.
## Version Number Format
The format of the version number is MAJOR.MINOR.PATCH, and the version number increment rule is as follows:
- MAJOR version when you make incompatible API changes,
- MINOR version when you add functionality in a backwards compatible manner,
- PATCH version when you make backwards compatible bug fixes.
- For more details, please refer to [Semantic Versioning 2.0.0](https://semver.org)
## Record Types
Init - Project initialization.
Added - Newly added features.
Changed - Changes to existing functionalities.
Deprecated - Soon to be deprecated features.
Removed - Features removed in this version.
Fixed - Any bug fixes.
Security - Patches and security improvements.
Note - Additional remarks regarding the version.
***************************************************
# Version Update History
## [0.0.19] - 2025-11-17
### Added
- Added AWS Bedrock model support
- Added ollama embedding component support
- Added jina rerank component support
- Added vector database component support
- Faiss vector database support
- Qdrant vector database support
- Added a batch of new Reader data loading components
- Added Notion, GoogleDoc, Confluence cloud document loading components
- Added file format support for epub, rar, sevenzip, zip, xlsx
- Added text extraction components for images and PDF files based on PaddleOCR
- Added web page loading components based on playwright and bs4
- Added GitHub and YouTube retrieval tools
- Added async safe exit method for McpSessionManager
- Added model Token consumption recording in the Otel-llm-instrumentor module
### Fixed
- Fixed parameter naming error in the RecursiveCharacterTextSplitter component's splitter method
- Fixed missing connection_kwargs parameter propagation in MCPToolkit
- Fixed abnormal queue release issue when tasks exited exceptionally in RequestTask
### Note
- Improved security for the SlsSender module's put method
- Enhanced robustness of loop event handling in logging_util
- Optimized reliability of the add_invocation_chain method in the Monitor module
- Included some third-party community examples and tools
- Performed additional code optimizations and documentation updates
## [0.0.18] - 2025-07-10
### Added
- Added observability capabilities for agent applications based on the OTel protocol
Established observation standards for aU agent applications based on OTel (OpenTelemetry) protocol. Comprehensive metrics and traces (including token consumption, latency, success rate, etc.) are collected across key components such as agents, LLMs, and tools. The implementation supports integration with mainstream observability frameworks including SigNoz, Jaeger, and Prometheus, enabling full lifecycle observability for agents.
- Added async Sink and Sender components for SLS Logger
### Fixed
- MCP service in Stdio mode now supports user-configurable environment parameter
### Note
- Third-party package dependency changes (Format: old version -> new version; single version means new)
- openai ("1.13.3" -> "1.55.3")
- opentelemetry-api ("^1.25.0")
- opentelemetry-sdk ("^1.25.0")
- opentelemetry-semantic-conventions (">=0.48b0")
- opentelemetry-exporter-otlp-proto-http ("^1.25.0")
- httpx ("0.27.2" -> ">=0.27.2")
- jsonlines ("^4.0.0")
- Other code optimizations and documentation updates
## [0.0.17] - 2025-05-22
### Added
- MCP Integration & Publishing Capabilities
Enables rapid integration with MCPServer for agent, and allows publishing tools/toolkits from aU as MCPServer services
- Toolkit Capabilities
Supports categorized management of tools and configuration for agent
- Knowledge Reader Components
- Added Yuque document loading component
- Added async_execute method to base tool class, enabling asynchronous tool invocation
- Added custom plugin extensions for trace collection processing
- Added configurations for the complete Qwen3 series model
### Changed
- Request Context Optimizations
### Deprecated
- ToolInput Object
The use of ToolInput object for tool parameters is deprecated (will be removed in 3 versions). See agentuniverse.agent.action.tool.common_tool for updated recommendations
### Note
- New Third-Party Dependencies
- mcp ("~=1.9.0")
- opentracing (">=2.4.0,<3.0.0")
- Other code optimizations and documentation updates
## [0.0.16] - 2025-04-17
### Added
- New Tool Plugins
- Added image text extraction tool based on OpenCV's OCR capabilities
- Added Shell command status query and execution tool
- Added universal file read/write tool
- Added Tavily intelligent search tool
- Knowledge Reader and Processing Components
- Added Feishu cloud document loader component
- Added universal code loader component
- Added code processing component based on AST (Abstract Syntax Tree)
- Support LLM model channel configuration, supporting model switching across different channel platform providers.
- Added Google Gemini 2.5 Pro model configuration.
- aU Agent supports integration with chatbox and CherryStudio clients. For details, refer to the [documentation](https://github.com/agentuniverse-ai/agentUniverse/blob/master/docs/guidebook/en/In-Depth_Guides/Tutorials/LLM/LLM_Channel.md).
### Note
- Change version constraints for third-party dependencies:
- tiktoken ('0.5.2' -> '<1.0.0')
- pydantic ('~2.6.4' -> '^2.6.4')
- Main branch regression tests passed for Python 3.10, 3.11, and 3.12
- Other code optimizations and documentation updates
## [0.0.15] - 2025-03-03
### Added
- New embedding components
- Azure-OpenAI embedding component
- Gemini embedding component
- Doubao embedding component
- New knowledge loading reader components
- Web page reader component based on BeautifulSoup (bs4)
- Image reader component based on OCR technology
- CSV format reader component
- New tool plugins
- Arxiv paper retrieval and query tool plugin
- Jina AI intelligent search tool plugin
- Added standard LLM output parser for reasoning-type models
- Added standard logger sink for agents, LLMs, and tools
- Added retry function annotation
### Changed
- Improved project configuration experience, with the following key optimizations:
- Project configuration now supports global PACKAGE path replacement. For details, see the PACKAGE_PATH_INFO parameter in the sample project's config.toml file.
- Supports user-defined configuration extensions and YAML function extensions. For details, see the EXTENSION_MODULES parameter in the sample project's config.toml file.
- Updated custom_key.toml.sample with more detailed parameter content.
- Submit a set of commonly used model configuration YAML files. For details, see the llm directory in the sample project.
- YAML configuration now supports user-defined loading of attributes using environment variables and extension functions. For details, see the api_key comments in the llm sample of the sample project.
- Simplified LLM configuration. By default, it reads the global default_llm configuration. For details, see the default_llm.toml configuration in the llm sample of the sample project.
- Simplified component extension configuration. The module part in the component metadata can be left blank, and it will default to searching for a Python extension file with the same name in the same directory.
- Optimized project startup process, with the following key improvements:
- Improved LLM component startup registration. Only LLM instances that are dependent on by components like agents and tools are started.
- Enhanced error info during project startup.
- Other changes:
- Renamed LocalMemoryStorage to RamMemoryStorage for memory storage objects.
### Note
- Added image_build image packaging files and tutorial documents for application projects.
- Added CONTRIBUTING.md documentation for the project.
- Standardized PR and ISSUE templates for the project.
- Added a sample practice for agents based on multimodal capabilities. For details, see the examples/multimodal_app directory in the project.
- Our project was included in the awesome-deepseek-integration list released by DeepSeek in February.
## [0.0.14] - 2025-01-26
### Added
- aU Memory Component Version Update
The new version provides comprehensive memory management and utilization capabilities for multi-agent applications through a global memory module. It can automatically collect, record, and process memory interactions among multiple agents, including conversations, model calls, tool calls, and knowledge retrieval. Additionally, it offers functionalities such as memory addition, memory retrieval, memory modification, memory compression, memory pruning, memory extraction, and multi-source persistence for both single-agent and multi-agent.
- Add AgentTemplate Component and WorkPattern Component
The AgentTemplate component helps users rapidly create agents according to pre-defined templates, while the WorkPattern component assists agent teams in selecting specific collaboration methods. In versions prior to V0.0.13, the Planner component offered both the customization logic of intelligent agents and their work patterns. The customization logic for agents was often modified due to the task, whereas work patterns were validated and stability. Consequently, users frequently needed to rewrite the Planner and focus on the code logic related to work patterns, which significantly increased their usage and development costs. With the new version, we have layered the customization logic and work patterns in the agent-building process. It will make the research on collaboration modes and the construction of intelligent agents more focused and efficient. The original Planner component will still be retained, but it will no longer be recommended.
- Knowledge Components Update
Add: Markdown format knowledge loading component, document chapter and paragraph segmentation component, knowledge graph storage component (beta version).
### Changed
- Standard Project Scaffolding Update
The scaffolding Project Scaffolding has been standardized. You can read the [「Application Project Structure and Explanation」](./docs/guidebook/en/Get_Start/1.Application_Project_Structure_and_Explanation.md) for more details. For users of older versions, we have provided some guidelines and tools for this update, detailed information can be found in [「aU Old and New Project Migration Guide」](./docs/guidebook/en/Get_Start/6.aU_Old_and_New_Project_Migration_Guide.md).
### Note
- Update docs for new memory version
- Optimization official docs and examples project
- Ask for high-priority features
# [0.0.13] - 2024-09-12
### Added
- RAG(Retrieval-Augmented Generation) Component Version Update
This version provides a standard operating procedure for knowledge base construction and the RAG retrieval recall stage. The component covers a series of RAG atomic capabilities, including data loading, data processing, index construction, knowledge storage, intent rewriting, and retrieval re-ranking, helping users to quickly build a general RAG intelligent agent solution in open-source scenarios.
- Intelligent Agent Product Platform Update
This version introduces new capabilities such as intelligent agent canvas orchestration, private knowledge base construction, and custom plugin support, enabling users to quickly build and orchestrate intelligent agents through a low-code, visual approach.
- Added GLM Default Model Component for Zhipu
- Added SQLiteStore Storage Component
- Added Flow Orchestration Execution Engine
### Note
- Default path optimization for system_db_uri
The default path is already compatible with the Windows platform, for more details, please refer to [issue142](https://github.com/antgroup/agentUniverse/issues/142)
- Support for configurable chain stop words in ReactAgent
The ReactAgent YAML configuration now supports the stop_sequence keyword, allowing users to customize chain stop words. For more details, please refer to [issue127](https://github.com/antgroup/agentUniverse/issues/127)
- Added an introduction to RAG principles and a quick guide for building RAG, please pay attention to the corresponding parts in the README and user guide.
- Added advanced guidance documents for the intelligent agent productization platform, please pay attention to the corresponding parts in the README and user guide.
- Various code optimizations and documentation updates.
## [0.0.12] - 2024-08-14
### Added
- agentUniverse Product Version Offering
- The current version provides basic capabilities for agent construction, modification, and debugging, jointly launched by the difizen project. For more details, please refer to the documentation in the product platform section.
- Monitor Component: Added knowledge and tool instance collection, supporting full-link trace sequence concatenation and providing token consumption monitoring.
- New Web Session Module: Provides session and message persistence management capabilities.
### Note
- Optimized Knowledge Component: Users can configure and specify any number of recall results (similarity_top_k).
- Fixed Chroma Component: Resolved issues where the embedding module was not specified.
- Various code optimizations and documentation updates.
## [0.0.11] - 2024-07-11
### Added
- DataAgent Autonomous Data Agent MVP Version Released
- Minimum Viable Product version, DataAgent aims to empower your agent with the capability of self-assessment and evolution through intelligent agent abilities. For detailed information, please refer to the user documentation.
- Added intermediate information streaming output capabilities in PEER and ReAct modes
### Note
- Latest PEER research findings released
- This paper provides a detailed introduction to the mechanisms and principles of the PEER multi-agent framework. Experimental validation proves the advancement of the PEER model. For detailed information, please refer to the user documentation.
- Added use cases
- Andrew Ng's Reflexive Workflow Translation Agent Replication
- Some code optimizations and documentation updates.
## [0.0.10] - 2024-06-28
### Added
- Added standard integration for the DeepSeek model in the LLM module.
- Added a new OpenAI general protocol wrapper class, OpenAIStyleLLM.
- Models using the OpenAI protocol can be configured directly.
- Added a new LangChain tool wrapper class, LangChainTool, with several example tools for search and execution.
- LangChain tools can be configured directly.
- Added Agent information collection capability in the monitor module.
### Note
- Added use cases.
- Supplemented documentation with a financial event analysis case study using PEER collaborative mode.
- Added several new documents for LLM components, tool components, and the Monitor module.
- Updated the new README.
- Some code optimizations and documentation updates.
## [0.0.9] - 2024-06-14
### Added
- Added standard integration for Claude and Ollama LLM components
- Added new Qwen embedding module
- Added default agents for ReAct-Type and NL2API-Type
### Note
- Added new use cases
- RAG-Type Agent Examples: Legal Consultation Agent
- ReAct-Type Agent Examples: Python Code Generation and Execution Agent
- Multi-Agent: Discussion Group Based on Multi-Turn Multi-Agent Mode
For more details, please refer to the use case section in the user documentation.
- Some code optimizations and documentation updates.
## [0.0.8] - 2024-06-06
### Added
- Introduced a new monitor module
- Data running in any agentUniverse can be collected and observed
- Added webserver post_fork functionality
- Provides multi-node process intervention capabilities after starting the webserver in agentUniverse
- Introduced SQLDB_WRAPPER wrapper class, offering typical database connection methods
- Through the SQLDB_WRAPPER wrapper class, you can conveniently connect to various databases and storage technologies including SQLServer, MySQL, Oracle, PostgreSQL, SQLite and others
- Added connection support for Milvus vector database component
For more usage of the above features, please pay attention to the agentUniverse guidebook.
### Changed
- Flask is set as the default webserver startup method across all platforms, with gunicorn and gRPC capabilities disabled by default
- In the previous version, we found slight compatibility differences with gunicorn and gRPC across different operating systems. Thus, we have made Flask the primary startup method for all platforms. You can enable gunicorn and gRPC in the configuration as needed.
### Security
- Some aU dependencies were identified to have security vulnerabilities in third-party packages. For security reasons, we have upgraded their versions, with the main changes including:
- requests (^2.31.0 -> ^2.32.0)
- flask (^2.2 -> ^2.3.2)
- werkzeug (^2.2.2 -> ^3.0.3)
- langchain (0.0.352 -> 0.1.20)
- langchain-core (0.1.3 -> 0.1.52)
- langchain-community (no version lock -> 0.0.38)
- gunicorn (21.2.0 -> ^22.0.0)
- Jinja2 (no version lock -> ^3.1.4)
- tqdm (no version lock -> ^4.66.3)
If your system has external access, we strongly recommend installing version v0.0.8 of agentUniverse to mitigate the security risks posed by these third-party packages. For more detailed information, you can visit https://security.snyk.io.
### Note
- Some code optimizations and documentation updates.
## [0.0.7] - 2024-05-29
### Added
- LLM component supports multimodal parameter invocation.
- Added LLM integration methods for Qwen, WenXin, Kimi, Baichuan, etc.
### Note
- Added a multimodal example agent, see the invocation details in `sample_standard_app.intelligence.test.test_multimodal_agent.MultimodalAgentTest`.
- Some code optimizations and documentation updates.
## [0.0.6] - 2024-05-15
### Added
- Support for the GPT-4o model, with updates to related examples.
- Support for the RPC component gRPC, providing a standard method for service startup.
### Note
- Provide standard Docker images and K8S deployment solutions.
- Some code optimizations and documentation updates.
## [0.0.5] - 2024-05-08
### Added
- The LLM component supports streaming calls.
- The Knowledge component adds an update definition.
### Fixed
- Fixed potential concurrency safety issues in the peer planner.
- Fixed the issue in version 0.0.4 of the PyPI package where the packaging method forced users to enter an AK upon startup.
### Note
- Some code optimizations and documentation updates.
## [0.0.4] - 2024-04-26
### Added
- Add version management capability to the prompt.
### Fixed
- Fixed compatibility issues on Windows
* Due to compatibility issues of Gunicorn with Windows systems, automatically identify the kernel version to select the web startup method.
* Specified YAML reading as UTF-8 encoding method.
### Note
- [2024-05-08] Please be aware that the PyPI package version 0.0.4 includes the sample_standard_app example project by default. This will reference additional components from sample_standard_app at startup and require users to input an AK. If you are not using the corresponding components, you can bypass this restriction by using a mock AK. This issue has been fixed in version 0.0.5.
## [0.0.3] - 2024-04-19
### Init
- The official release version of agentUniverse has been initialized. Enjoy using it!
## [0.0.2] - 2024-04-17
### Fixed
- Fixed an issue where associated dependencies were not being automatically installed when installing package versions.
## [0.0.1] - 2024-04-09
### Init
- Project initialization commit. This framework is a large model multi-agent framework. Enjoy using it!
+344
View File
@@ -0,0 +1,344 @@
# 版本说明
**************************************
语言版本: [简体中文](CHANGELOG_zh.md) | [English](CHANGELOG.md)
本文件用于记录项目的版本更新历史。
## 版本号格式
版本号格式为 `主版本号.次版本号.修订号`,版本号递增规则如下:
- 主版本号:当你做了不兼容的 API 修改时,递增主版本号。
- 次版本号:当你做了向下兼容的功能性新增时,递增次版本号。
- 修订号:当你做了向下兼容的问题修正时,递增修订号。
- 详细说明请参考 [语义化版本 2.0.0](https://semver.org)
## 记录类型
Init - 项目初始化。
Added - 新增的功能。
Changed - 对现有功能的更改。
Deprecated - 即将废弃的功能。
Removed - 现版本中移除的功能。
Fixed - 任何错误修复。
Security - 补丁与安全改进。
Note - 对于版本的额外说明。
***************************************************
# 版本更新记录
## [0.0.19] - 2025-11-17
### Added
- 新增AWS Bedrock模型支持
- 新增ollama embedding组件支持
- 新增jina rerank组件支持
- 新增向量数据库组件支持
- 新增Faiss向量数据库支持
- 新增Qdrant向量数据库支持
- 新增一批Reader数据加载组件支持
- 新增Notion、GoogleDoc、Confluence云文档加载组件
- 新增epub、rar、sevenzip、zip、xlsx等格式文件加载组件
- 新增基于PaddleOCR的图像与pdf文件文字提取组件
- 新增基于playwright、bs4的网页加载组件
- 新增github、youtube检索工具
- 新增McpSessionManager异步安全退出方法
- 模块Otel-llm-instrumentor新增模型Token消耗记录
### Fixed
- 修复RecursiveCharacterTextSplitter组件splitter方法参数命名错误问题
- 修复MCPToolkit中connection_kwargs参数传递丢失问题
- 修复RequestTask中任务异常退出队列释放异常问题
### Note
- SlsSender模块put方法安全性优化
- logging_util中loop event健壮性优化
- Monitor模块add_invocation_chain方法健壮性优化
- 部分第三方社区案例、工具收录
- 其他代码优化与文档更新
## [0.0.18] - 2025-07-10
### Added
- 新增基于OTel协议的智能体应用可观测能力
制定aU智能体应用的观测标准,基于OTel(OpenTelemetry)协议,对智能体、模型、工具等关键组件的token消耗、耗时、成功率等核心指标以及调用链(trace)进行全面采集与观测,并适配 SigNoz、Jaeger、Prometheus 等主流观测框架,从而实现对智能体全生命周期的可观测性支持。
- 新增异步SLS日志Sink、Sender组件
### Fixed
- MCP服务调用Stdio模式下env参数支持用户配置透传
### Note
- 第三方包依赖变更(格式:原版本->新版本,只包含一个版本号为新引入)
- openai ("1.13.3" -> "1.55.3")
- opentelemetry-api ("^1.25.0")
- opentelemetry-sdk ("^1.25.0")
- opentelemetry-semantic-conventions (">=0.48b0")
- opentelemetry-exporter-otlp-proto-http ("^1.25.0")
- httpx ("0.27.2" -> ">=0.27.2")
- jsonlines ("^4.0.0")
- 其他代码优化与文档更新
## [0.0.17] - 2025-05-22
### Added
- 新增MCP接入与发布能力
- 通过该功能可快速接入MCPServer供智能体使用,亦可将aU中的工具/工具集合发布成为MCPServer对外服务
- 新增工具包ToolKit能力
- 可对于一系列工具进行分类管理并供智能体配置使用
- 新增知识Reader与加工组件
- 新增语雀文档加载组件
- 工具基类中新增async_execute方法,开放工具异步调用能力
- trace模块新增自定义插件扩展,支持自定义处理trace采集内容
- 新增千问3系列模型配置
### Changed
- Request上下文优化
### Deprecated
- ToolInput对象废弃
工具入参ToolInput对象写法已不推荐(将在3个版本后废弃),可关注agentuniverse.agent.action.tool.common_tool最新推荐写法
### Note
- 新增第三方包依赖
- mcp ("~=1.9.0")
- opentracing (">=2.4.0,<3.0.0")
- 其他代码优化与文档更新
## [0.0.16] - 2025-04-17
### Added
- 新增工具插件
- 新增基于opencv图像OCR能力的图片文字提取工具
- 新增shell命令状态查询与执行工具
- 新增通用文件读写工具
- 新增Tavily智能搜索工具
- 新增知识Reader与加工组件
- 新增飞书云文档加载组件
- 新增通用代码加载组件
- 新增基于AST(Abstract Syntax Tree)代码处理组件
- 新增llm模型通道配置能力,支持模型基于不同通道平台提供方进行切换,详情可见[文档](https://github.com/agentuniverse-ai/agentUniverse/blob/master/docs/guidebook/zh/In-Depth_Guides/%E5%8E%9F%E7%90%86%E4%BB%8B%E7%BB%8D/%E6%A8%A1%E5%9E%8B/%E6%A8%A1%E5%9E%8B%E9%80%9A%E9%81%93.md)
- 新增Google gemini 2.5 pro模型配置
- 支持aU智能体配置接入chatbox、CherryStudio客户端,详情可见[文档](https://github.com/agentuniverse-ai/agentUniverse/blob/master/docs/guidebook/zh/How-to/%E4%BD%BF%E7%94%A8chatbox%E7%AD%89%E5%B7%A5%E5%85%B7%E8%BF%9E%E6%8E%A5aU/%E5%A6%82%E4%BD%95%E4%BD%BF%E7%94%A8chatbox%E7%AD%89%E5%B7%A5%E5%85%B7%E8%BF%9E%E6%8E%A5agentUniverse.md)
### Note
- 部分依赖第三方包版本限制放开
- tiktoken ('0.5.2' -> '<1.0.0')
- pydantic ('~2.6.4' -> '^2.6.4')
- 基于Python3.10、3.11与3.12版本的主干回归通过
- 其他代码优化与文档更新
## [0.0.15] - 2025-03-03
### Added
- embedding组件新增
- 新增azure-openai embedding组件
- 新增gemini embedding组件
- 新增豆包embedding标准组件
- 知识加载reader组件新增
- 新增基于bs4的网页读取组件
- 新增基于OCR技术的图像加载组件
- 新增csv格式表格加载组件
- 工具插件新增
- 新增Arxiv文献检索查询工具插件
- 新增Jina AI智能搜索工具插件
- 新增reasoning类模型标准LLM输出解析器
- 新增agent、llm、tool相关日志采集标准logger
- 新增retry函数注解
### Changed
- 项目配置体验优化,主要优化点如下
- 项目配置支持全局PACKAGE路径替换,详情见样例工程config.toml文件PACKAGE_PATH_INFO参数部分
- 支持用户自定义配置扩展与yaml函数扩展,详情见样例工程config.toml文件EXTENSION_MODULES参数部分
- custom_key.toml.sample更新,提供更详细与全面的参数内容
- 内置一批常用模型配置yaml,详情见样例工程llm目录
- yaml配置支持用户使用环境变量与扩展函数自定义加载对应属性,详情见样例工程llm样例中api_key注释说明部分
- llm配置简化,默认读取全局default_llm配置,详情见样例工程llm样例default_llm.toml配置内容
- 组件扩展配置简化,组件metadata中module部分可不填写,默认寻找同层级同名py扩展文件
- 项目启动流程优化,主要优化点如下
- LLM组件启动注册优化,只启动用户在agent、tool等组件中依赖启动的LLM实例
- 项目启动报错提示优化
- 其他变更
- 内存记忆存储对象LocalMemoryStorage更名RamMemoryStorage
### Note
- 新增应用工程image_build镜像打包文件与教程文档
- 新增项目贡献者开发文档
- 规范项目PR与ISSUE模版
- 新增基于模型多模态能力的agent样例实践,详情见项目examples/multimodal_app
- 项目于2月收录于deepseek发布的awesome-deepseek-integration榜单
## [0.0.14] - 2025-01-26
### Added
- aU记忆机制全面改版升级
新版aU记忆通过全局记忆模块为多智能体应用提供全面的记忆管理和使用能力,它能够自动采集、记录和处理多智能体之间的对话、模型调用、工具调用、知识检索等记忆过程。同时,还为单智能体与多智能体提供记忆新增、记忆检索、记忆修改、记忆压缩、记忆裁剪、记忆提取以及记忆多源持久化等功能。
- 新增智能体模版(AgentTemplate)与工作模式(WorkPattern)组件
智能体模板(AgentTemplate)组件帮助用户快速根据已经沉淀的模版搭建智能体,工作模式组件帮助智能体组快速选择复用特定的智能体协作方式。在V0.0.13之前的版本中,计划(Planner)组件承载了智能体的定制逻辑与工作模式,智能体的定制逻辑经常会因为实际任务需求被修改,而工作模式是验证有效稳定的,用户往往需要复写Planner并关注工作模式的代码逻辑,这大大增加了用户的使用与研发成本。通过本次改版我们将智能体构建中的定制逻辑与工作模式分层,这将使协同模式研究与智能体构建过程更加聚焦与高效。原有的计划(Planner)组件仍将会保留,但不再被推荐。
- 部分知识组件新增与优化
新增组件:markdown格式知识加载组件、文档章节段落切分组件、图谱知识存储组件(beta版)
### Changed
- 标准脚手架工程结构改版
脚手架工程结构规范化,您可阅读 [「标准应用工程结构说明」](./docs/guidebook/zh/开始使用/1.标准应用工程结构说明.md) 了解详情。对于旧版本的用户我们为这次改版提供了一些指南说明与工具,详情可阅读 [「aU新老工程迁移指南」](./docs/guidebook/zh/开始使用/6.aU新老工程迁移指南.md)。
### Note
- 新增aU新版记忆机制文档介绍
通过[「aU记忆机制介绍」](./docs/guidebook/zh/开始使用/1.标准应用工程结构说明.md)与[「新版记忆使用说明」](./docs/guidebook/zh/How-to/定义与使用全局记忆/如何使用全局记忆.md)文档了解本次版本更新内容。
- 官方文档与实践案例优化改版
- 高优feature公布与征集
## [0.0.13] - 2024-09-12
### Added
- RAG检索增强能力组件版本更新
本版本提供知识库构建、RAG检索召回环节标准作业流程,组件覆盖数据加载、数据处理、索引构建、知识入库、意图改写、检索重排等一系列RAG原子能力,帮助用户在开源场景下快速构建通用RAG智能体方案。
- 智能体产品化平台更新
本版本新增支持智能体画布编排、私有知识库构建、自定义插件等能力,通过低代码、可视化的方式帮助用户快速构建与编排智能体。
- 新增智谱GLM默认模型组件
- 新增SQLiteStore存储组件
- 新增flow编排执行引擎
### Note
- system_db_uri默认路径优化
默认路径已兼容windows平台,详情见[issue142](https://github.com/agentuniverse-ai/agentUniverse/issues/142)
- ReactAgent支持链停止词配置化
ReactAgent yaml配置目前已经支持stop_sequence关键词,用户可以自行配置链停止词,详情见[issue127](https://github.com/agentuniverse-ai/agentUniverse/issues/127)
- 新增RAG原理介绍与RAG快速构建指导文档,请关注README与用户指南相应部分。
- 新增智能体产品化平台高阶指导文档,请关注README与用户指南相应部分。
- 部分代码优化与文档更新
## [0.0.12] - 2024-08-14
### Added
- agentUniverse产品化版本提供
- 当前版本提供智能体构建、修改、调试等基础能力,由difizen项目联合推出,更多详情请见文档产品化平台部分。
- monitor组件新增对于知识、工具实例采集,支持全链路trace时序串联并提供token消耗监控
- 新增web会话模块,提供session与message持久化管理能力
### Note
- 优化知识组件,可由用户配置指定任意召回结果数量(similarity_top_k)
- 修复chroma组件未指定embedding模块出现异常
- 其他部分代码优化与文档更新
## [0.0.11] - 2024-07-11
### Added
- DataAgent数据自治智能体MVP版本发布
- Minimum Viable Product版本,DataAgent旨在使用智能体能力让您的Agent拥有自我评价与演进的能力,详细内容请查阅用户文档。
- 增加PEER、ReAct模式中间信息流式输出能力
### Note
- PEER最新研究成果发布
- 该文献详细介绍了PEER多智能体框架的机制原理,同时在实验部分通过验证证明了PEER模式的先进性,详细内容请查阅用户文档。
- 新增使用案例
- 吴恩达反思工作流翻译智能体复刻
- 部分代码优化与文档更新
## [0.0.10] - 2024-06-28
### Added
- LLM组件新增DeepSeek模型标准接入
- 新增OpenAI通用协议包装类OpenAIStyleLLM
- openai协议类模型接入可直接配置
- 新增LangChain工具包装类LangChainTool,新增搜索类、执行类示例工具若干
- LangChain工具接入可直接配置
- monitor模块新增Agent纬度信息采集能力
### Note
- 新增使用案例
- PEER协同模式的金融事件分析案例文档补充
- 新增若干LLM组件、工具组件、Monitor模块文档
- 新版README更新
- 部分代码优化与文档更新
## [0.0.9] - 2024-06-14
### Added
- LLM组件新增claude、ollama标准接入
- 新增qwen embedding模块
- 新增ReAct、nl2api默认agent
### Note
- 新增使用案例
- RAG类Agent案例-法律咨询Agent
- ReAct类Agent案例-Python代码生成与执行Agent
- 多智能体案例-基于多轮多Agent的讨论小组
详情请看用户文档案例部分。
- 部分代码优化与文档更新
## [0.0.8] - 2024-06-06
### Added
- 新增monitor模块
- 任何agentUniverse运行时的数据可以被采集与观测
- 新增webserver post_fork功能
- 开放agentUniverse中webserver启动后的多节点流程干预功能
- 新增SQLDB_WRAPPER包装类,提供典型数据库连接方式
- 通过SQLDB_WRAPPER包装类您可以非常方便的连接如SQLServer、MySQL、Oracle、PostgreSQL、SQLite等几十种数据库与存储技术组件。
- 新增milvus向量数据库组件连接
上述功能更多用法请关注agentUniverse指导手册部分。
### Changed
- 全平台以flask作为默认webserver启动方式,gunicorn与GRPC能力置为默认关闭
- 我们在上个版本中发现不同的操作系统对于gunicorn与GRPC的兼容性会有略微差异,我们将flask作为全平台的第一启动方式,您可以按需在配置中开启gunicorn与GRPC。
### Security
- 部分aU依赖第三方包识别到安全漏洞,出于安全考虑我们对其进行版本升级,主要包含如下变动:
- requests (^2.31.0 -> ^2.32.0)
- flask (^2.2 -> ^2.3.2)
- werkzeug (^2.2.2 -> ^3.0.3)
- langchain (0.0.352 -> 0.1.20)
- langchain-core (0.1.3 -> 0.1.52)
- langchain-community (no version lock -> 0.0.38)
- gunicorn (21.2.0 -> ^22.0.0)
- Jinja2 (no version lock -> ^3.1.4)
- tqdm (no version lock -> ^4.66.3)
若您的系统存在外部访问,强烈建议您安装v0.0.8版本的aU以规避这些三方包的安全风险,更详细的说明您可以关注https://security.snyk.io。
### Note
- 部分代码优化与文档更新
## [0.0.7] - 2024-05-29
### Added
- LLM组件支持多模态参数调用
- 新增通义千问、文心一言、Kimi、百川等常用LLM接入方式
### Note
- 添加多模态样例agent调用详情见`sample_standard_app.intelligence.test.test_multimodal_agent.MultimodalAgentTest`
- 部分代码优化与文档更新
## [0.0.6] - 2024-05-15
### Added
- 支持gpt-4o模型, 并更新相关样例
- 支持RPC组件gGpc,并提供标准服务启动方法
### Note
- 提供标准的aU Docker镜像与K8S部署方案,详情见指导手册
- 部分代码优化与文档更新
## [0.0.5] - 2024-05-08
### Added
- LLM组件支持流式调用
- 知识组件添加update定义
### Fixed
- 修复peer planner中可能存在的并发安全性隐患
- 修复0.0.4版本中pypi package打包方式导致启动强制要求用户填写AK问题
### Note
- 追加部分代码优化与文档更新
## [0.0.4] - 2024-04-26
### Added
- 新增prompt版本管理能力
### Fixed
- Windows版本下的兼容问题修复
* 由于Gunicore对于windows系统的兼容问题,自动识别内核版本自动选择web启动方式
* yaml读取指定为utf-8 encode方式
### Note
- [2024-05-08] 注意,0.0.4的pypi package版本中默认包含了sample_standard_app示例工程, 这将会在启动时引用sample_standard_app中的额外组件,并要求用户填写AK, 若您没有使用对应组件可以通过mock ak跳过这一限制, 这已经在0.0.5版本中修复。
## [0.0.3] - 2024-04-19
### Init
- agentUniverse正式外发版本初始化,祝您使用愉快!
## [0.0.2] - 2024-04-17
### Fixed
- 修复安装包版本时无法自动安装关联依赖包问题。
## [0.0.1] - 2024-04-09
### Init
- 项目初始化提交,本框架是一个大模型多智能体框架,祝您使用愉快!
+73
View File
@@ -0,0 +1,73 @@
**🎈🎈🎈 Welcome to agentUniverse!🎉🎉🎉**
Thank you for your interest in agentUniverse and your willingness to contribute. We welcome you to join the agentUniverse community family. As an open-source project in the field of artificial intelligence, your contributions are important to the development and improvement of our project. We welcome all types of contributions, such as introducing new features, fixing code issues, improving documentation, submitting issues, and adding examples.
### Communicate with Us
If you have any ideas or questions related to contributions, feel free to reach out to us in advance. You can communicate through the [issue](https://github.com/antgroup/agentUniverse/issues) section of the agentUniverse project, send us an email, or join our community for discussions. For more detailed communication methods, please refer to the [Contact Information](docs/guidebook/en/Contact_Us.md)。
### Guidelines
#### Contributing to the Code & Docs
The contribution process for code and documentation in this project fully follows the standard procedures of the GitHub community. You can refer to the official GitHub [Fork-and-Pull-Request](https://docs.github.com/en/get-started/exploring-projects-on-github/contributing-to-a-project) documentation for detailed operational steps.
During the commit submission process, this project follows part of the Angular git commit conventions, and you are required to tag the corresponding type in your commit messages.
Here is the list of commit types:
* feat: New feature (e.g., feat: add Agent Template feature)
* fix: Bug fix (e.g., fix: fix memory leak in framework core)
* docs: Documentation update (e.g., docs: update agent usage guide documentation)
* refactor: Code refactoring that does not involve changes to functionality (e.g., refactor: refactor knowledge processing module code)
* test: Testing-related submissions or tools (e.g., test: add unit tests for agent loading module)
* chore: Other changes (e.g., chore: replace project icon image)
##### Guideline for PR
During the PR submission process, we follow the aforementioned commit types. You can choose the type as a PR label based on the main content of your submission.
Please ensure that you meet the following requirements when submitting your PR:
- Read and understand the requirements outlined in the [Contributor Guidelines](https://github.com/antgroup/agentUniverse/blob/master/CONTRIBUTING.md).
- Check for any duplicate features related to this request and communicated with the project maintainers.
- Accept the suggestion of the maintainers to make changes to or close this PR.
- Submit the test files and can provide screenshots of the test results (required for feature or bug fixes).
- Add or modified the documentation related to this PR.
- Add examples and notes if needed.
- Carefully fill out the PR request, including assigning maintainers, providing a detailed description of the PR content, and including necessary explanations and screenshots.
#### Guideline for development
We recommend following the [python PEP8](https://peps.python.org/pep-0008/) and [Google Python Style](https://google.github.io/styleguide/pyguide.html) guidelines.
If you are new in Python language, there is no need to feel pressured by these standards; just focus on the following basic guidelines:
##### Naming Conventions
Refer to the [Naming Styles](https://peps.python.org/pep-0008/#naming-conventions) in PEP8.
##### Commenting Standards
Provide comments in the following sample format, including function descriptions, Args parameters, Returns values, and Raises error information, etc.
```python
def connect_to_next_port(self, minimum: int) -> int:
"""Connects to the next available port.
Args:
minimum: A port value greater or equal to 1024.
Returns:
The new minimum port.
Raises:
ConnectionError: If no available port is found.
"""
if minimum < 1024:
# Note that this raising of ValueError is not mentioned in the doc
# string's "Raises:" section because it is not appropriate to
# guarantee this specific behavioral reaction to API misuse.
raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
port = self._find_next_open_port(minimum)
if port is None:
raise ConnectionError(
f'Could not connect to service on port {minimum} or higher.')
# The code does not depend on the result of this assert.
assert port >= minimum, (
f'Unexpected port {port} when minimum was {minimum}.')
return port
```
#### Contributing to article & examples
If you have used the agentUniverse project and are satisfied with it, we welcome you to share your case studies in the project community or on any media platform. We will periodically hold community events to comment, encourage, and promote outstanding cases and developers.
+71
View File
@@ -0,0 +1,71 @@
**🎈🎈🎈 欢迎来到agentUniverse!🎉🎉🎉**
感谢您对agentUniverse的关注并有意愿为项目做出贡献,欢迎您加入agentUniverse的社区大家庭。作为一个人工智能领域的开源项目,您的贡献对我们项目的发展和改进至关重要。我们欢迎各种类型的贡献参与,如新功能引入、代码修复、文档改进、issue提交、案例添加等。
### 与我们沟通
如果您有任何贡献相关的想法与疑问可以提前与我们进行沟通,您可以在agentUniverse的项目的[issue](https://github.com/antgroup/agentUniverse/issues) 、发送邮件、或加入我们的社群进行沟通,更详细的沟通方式可见[联系方式](docs/guidebook/zh/联系我们.md)。
### 贡献指南
#### 项目代码与文档贡献
本项目的代码与文档贡献流程完全遵循github社区的标准流程,详细的操作步骤您可以参考github官方发布的[Fork-and-Pull-Request文档](https://docs.github.com/en/get-started/exploring-projects-on-github/contributing-to-a-project) 。
在提交commit的过程中,本项目参考沿用了部分git-commit Angular规范,在commit提交中需要您标记对应的类型。
commit类型列表:
* feat: 新功能 (如,feat:新增Agent Template功能)
* fix: bug修复 (如,fix:框架内核内存泄漏修复)
* docs: 文档更新 (如,docs: 智能体使用指导文档更新)
* refactor: 代码重构,不涉及功能改动的代码重构 (如, refactor: 知识加工模块代码重构)
* test: 测试类或工具提交 (如, test: 添加智能体加载模块单元测试)
* chore: 其他杂项 (如, chore: 项目icon图片替换)
##### Pull Request规范
在PR的提交过程中,我们沿用了上述commit类型,您可在PR提交中根据主要内容选择对应类型作为PR标签。
请您确保在提交PR时满足如下要求:
- 阅读并理解[贡献者指南](https://github.com/antgroup/agentUniverse/blob/master/CONTRIBUTING_zh.md) 的要求。
- 检查没有与此PR请求重复的功能并与项目维护者进行了沟通。
- 接受PR配合维护人员的建议进行修改或关闭。
- 提交测试文件并提供测试结果截图(功能修改、BUG修复类PR必须提供,其他按需)
- 添加或修改本次pr对应的文档说明(非必要,根据实际PR内容按需添加)
- 添加使用案例代码与文档说明(非必要,根据实际PR内容按需添加)
- 认真填写PR请求,包括指定维护人员、详细描述PR内容、提供必要的说明与截图等
#### 研发规范参考
在代码与注释规范方面,本项目推荐采用[python PEP8](https://peps.python.org/pep-0008/) 与 [Google Python Style](https://google.github.io/styleguide/pyguide.html) 规范。
若您对于python语言不是特别熟悉,不必对于这些规范感到压力,重点关注如下基本规范即可:
##### 命名规范
参考PEP8中的 [Naming Styles](https://peps.python.org/pep-0008/#naming-conventions) 部分。
##### 注释规范
按如下样例格式提供注释,如功能、Args参数、Returns返回、Raises报错信息等。
```python
def connect_to_next_port(self, minimum: int) -> int:
"""Connects to the next available port.
Args:
minimum: A port value greater or equal to 1024.
Returns:
The new minimum port.
Raises:
ConnectionError: If no available port is found.
"""
if minimum < 1024:
# Note that this raising of ValueError is not mentioned in the doc
# string's "Raises:" section because it is not appropriate to
# guarantee this specific behavioral reaction to API misuse.
raise ValueError(f'Min. port must be at least 1024, not {minimum}.')
port = self._find_next_open_port(minimum)
if port is None:
raise ConnectionError(
f'Could not connect to service on port {minimum} or higher.')
# The code does not depend on the result of this assert.
assert port >= minimum, (
f'Unexpected port {port} when minimum was {minimum}.')
return port
```
#### 文章与案例贡献
如果您使用agentUniverse项目并感到满意,欢迎您在项目社区或者任何您熟悉的媒体平台中分享您的案例,我们会不定期举行社区交流活动,赞扬、鼓励与传播那些优秀案例与开发者。
+201
View File
@@ -0,0 +1,201 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright 2024 Alipay
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
+909
View File
@@ -0,0 +1,909 @@
# Phase 3-4 Integration Guide
## Context Engineering System Integration
**Date**: 2025-12-04
**Status**: ✅ Phase 3 Complete | Phase 4 Integration Guide
---
## Overview
This guide demonstrates how to integrate the Phase 3-4 Context Engineering System with agentUniverse agents. The system provides:
1. **Knowledge-Context Synchronization** (Phase 3)
2. **Benchmarking Framework** (Phase 3)
3. **Agent Integration Patterns** (Phase 4)
4. **Cross-Agent Context Sharing** (Phase 4)
5. **Production Monitoring** (Phase 4)
---
## Phase 3: New Components
### 1. Knowledge-Context Synchronization
**Location**: `agentuniverse/agent/context/sync/knowledge_context_synchronizer.py`
**Purpose**: Bidirectional synchronization between Knowledge and Context systems with conflict resolution.
#### Key Features
- **4 Conflict Resolution Strategies**:
- `NEWEST_WINS`: Most recent knowledge takes precedence
- `CRITICAL_PRESERVED`: CRITICAL priority segments always kept
- `MERGE`: Combine both versions
- `VERSION_BOTH`: Keep both as versioned segments
- **Version Tracking**: SHA256 hash-based change detection
- **Selective Invalidation**: Mark outdated segments without deletion
- **Efficient Updates**: Only sync when content changes
#### Basic Usage
```python
from agentuniverse.agent.context.sync.knowledge_context_synchronizer import (
KnowledgeContextSynchronizer,
ConflictResolutionStrategy
)
from agentuniverse.agent.context.context_manager_manager import ContextManagerManager
# Get context manager instance
context_manager = ContextManagerManager().get_instance_obj("default_context_manager")
# Create synchronizer
synchronizer = KnowledgeContextSynchronizer(
context_manager=context_manager,
conflict_strategy=ConflictResolutionStrategy.NEWEST_WINS,
enable_versioning=True
)
# Sync knowledge to context
result = synchronizer.sync_knowledge_to_context(
knowledge_id="user_manual_v2",
documents=["Updated user manual content...", "New API documentation..."],
session_id="session_123",
source="knowledge_base",
priority=ContextPriority.HIGH
)
print(f"Added {result.segments_added} segments")
print(f"Invalidated {result.segments_invalidated} old segments")
```
#### Update Existing Knowledge
```python
# Update when knowledge changes
result = synchronizer.update_knowledge_context(
knowledge_id="user_manual_v2",
session_id="session_123",
new_documents=["Updated content with corrections..."],
conflict_strategy=ConflictResolutionStrategy.CRITICAL_PRESERVED
)
print(f"Resolved {result.conflicts_resolved} conflicts")
print(f"Updated {result.segments_updated} segments")
```
#### Version Tracking
```python
# Get version information
version = synchronizer.get_knowledge_version("user_manual_v2")
if version:
print(f"Version ID: {version.version_id}")
print(f"Source: {version.source}")
print(f"Hash: {version.hash}")
print(f"Timestamp: {version.timestamp}")
# List all versions
all_versions = synchronizer.list_knowledge_versions()
for knowledge_id, version in all_versions.items():
print(f"{knowledge_id}: {version.version_id}")
```
### 2. Benchmarking Framework
**Location**: `agentuniverse/agent/context/benchmark/benchmark_suite.py`
**Purpose**: Comprehensive evaluation against industry standards (Cursor, Claude).
#### Benchmark Targets
| Metric | Target | Description |
|--------|--------|-------------|
| Multi-turn coherence | >0.85 | Context preservation across turns |
| Compression ratio | 60-80% | Token reduction efficiency |
| Information loss | <10% | Semantic preservation |
| Retrieval precision | >0.90 | Search accuracy |
| Retrieval latency | <100ms | Search speed |
| Memory usage | <500MB | For 10K turns |
#### Basic Usage
```python
from agentuniverse.agent.context.benchmark.benchmark_suite import (
ContextBenchmarkSuite
)
from agentuniverse.agent.context.context_manager_manager import ContextManagerManager
# Get context manager
context_manager = ContextManagerManager().get_instance_obj("default_context_manager")
# Create benchmark suite
suite = ContextBenchmarkSuite(context_manager)
# Run full benchmark (100 turns by default)
result = suite.run_full_suite(num_turns=100)
# Check results
print(f"Overall Score: {result.metrics.get_score():.1f}/100")
print(f"Passes Targets: {result.metrics.passes_targets()}")
print(f"Multi-turn Coherence: {result.metrics.multi_turn_coherence:.3f}")
print(f"Compression Ratio: {result.metrics.compression_ratio:.1%}")
print(f"Information Loss: {result.metrics.information_loss:.1%}")
print(f"Retrieval Precision: {result.metrics.retrieval_precision:.3f}")
print(f"Average Latency: {result.metrics.average_latency_ms:.1f}ms")
print(f"Memory Usage: {result.metrics.memory_usage_mb:.1f}MB")
```
#### Detailed Metrics
```python
# Access detailed metrics
metrics = result.metrics
# Coherence metrics
print(f"Multi-turn coherence: {metrics.multi_turn_coherence:.3f}")
print(f"Context consistency: {metrics.context_consistency:.3f}")
# Compression metrics
print(f"Compression ratio: {metrics.compression_ratio:.1%}")
print(f"Information loss: {metrics.information_loss:.1%}")
print(f"Context preservation: {metrics.context_preservation:.1%}")
# Retrieval metrics
print(f"Precision: {metrics.retrieval_precision:.3f}")
print(f"Recall: {metrics.retrieval_recall:.3f}")
print(f"F1 Score: {metrics.retrieval_f1:.3f}")
# Performance metrics
print(f"Average latency: {metrics.average_latency_ms:.1f}ms")
print(f"P95 latency: {metrics.p95_latency_ms:.1f}ms")
print(f"P99 latency: {metrics.p99_latency_ms:.1f}ms")
print(f"Throughput: {metrics.throughput_ops_per_sec:.1f} ops/sec")
# Resource metrics
print(f"Memory usage: {metrics.memory_usage_mb:.1f}MB")
print(f"Tokens per turn (avg): {metrics.tokens_per_turn_avg:.1f}")
```
---
## Phase 4: Agent Integration Patterns
### Pattern 1: Context-Aware Agent (Basic)
**Use Case**: Single agent with context management
**Configuration** (`agent_context_aware.yaml`):
```yaml
name: 'context_aware_agent'
description: 'Agent with advanced context management'
profile:
llm_model:
name: 'gpt-4'
max_tokens: 2000
# Enable context manager
context_manager_name: 'default_context_manager'
task_type: 'dialogue' # code_generation, data_analysis, dialogue
system_prompt: |
You are an intelligent assistant with advanced context awareness.
You can maintain coherent conversations across multiple turns.
memory:
name: 'demo_memory'
action:
knowledge:
- 'demo_knowledge'
plan:
planner:
name: 'react_planner'
```
**Implementation**:
```python
from agentuniverse.agent.agent import Agent
from agentuniverse.agent.agent_manager import AgentManager
from agentuniverse.agent.context.context_manager_manager import ContextManagerManager
class ContextAwareAgent(Agent):
"""Agent with integrated context management."""
def __init__(self):
super().__init__()
self._context_manager = None
def initialize_by_component_configer(self, component_configer):
"""Initialize with context manager."""
super().initialize_by_component_configer(component_configer)
# Get context manager name from profile
context_manager_name = self.agent_model.profile.get('context_manager_name')
if context_manager_name:
self._context_manager = ContextManagerManager().get_instance_obj(
context_manager_name
)
return self
def pre_parse_input(self, input_object):
"""Enhanced input parsing with context extraction."""
agent_input = super().pre_parse_input(input_object)
# If context manager is enabled
if self._context_manager:
session_id = input_object.get_data('session_id')
if session_id:
# Create or get context window
task_type = self.agent_model.profile.get('task_type', 'dialogue')
window = self._context_manager.create_context_window(
session_id=session_id,
agent_id=self.agent_model.info.get('name'),
task_type=task_type
)
# Add user input to context
user_input = input_object.get_data('input')
if user_input:
self._context_manager.add_context(
session_id,
user_input,
ContextType.CONVERSATION,
ContextPriority.HIGH,
metadata={'role': 'user'}
)
# Add system prompt to context (CRITICAL priority)
system_prompt = self.agent_model.profile.get('system_prompt')
if system_prompt:
self._context_manager.add_context(
session_id,
system_prompt,
ContextType.SYSTEM,
ContextPriority.CRITICAL
)
# Get context for building agent input
agent_input['context_window'] = window
return agent_input
def parse_result(self, agent_result):
"""Enhanced result parsing with context storage."""
result = super().parse_result(agent_result)
# Store agent output in context
if self._context_manager:
session_id = agent_result.get('session_id')
output = result.get('output')
if session_id and output:
self._context_manager.add_context(
session_id,
output,
ContextType.CONVERSATION,
ContextPriority.HIGH,
metadata={'role': 'assistant'}
)
return result
```
### Pattern 2: Knowledge-Integrated Agent
**Use Case**: Agent with automatic knowledge-context synchronization
**Implementation**:
```python
from agentuniverse.agent.context.sync.knowledge_context_synchronizer import (
KnowledgeContextSynchronizer
)
class KnowledgeIntegratedAgent(ContextAwareAgent):
"""Agent with knowledge-context synchronization."""
def __init__(self):
super().__init__()
self._synchronizer = None
def initialize_by_component_configer(self, component_configer):
"""Initialize with synchronizer."""
super().initialize_by_component_configer(component_configer)
# Create synchronizer if context manager exists
if self._context_manager:
self._synchronizer = KnowledgeContextSynchronizer(
context_manager=self._context_manager,
enable_versioning=True
)
return self
def execute(self, input_object, agent_input):
"""Execute with knowledge synchronization."""
session_id = input_object.get_data('session_id')
# Sync knowledge before execution
if self._synchronizer and session_id:
knowledge_configs = self.agent_model.action.get('knowledge', [])
for knowledge_config in knowledge_configs:
knowledge_name = knowledge_config.get('name') if isinstance(knowledge_config, dict) else knowledge_config
# Get knowledge documents (simplified)
from agentuniverse.agent.action.knowledge.knowledge_manager import KnowledgeManager
knowledge = KnowledgeManager().get_instance_obj(knowledge_name)
if knowledge:
# Query relevant documents
query = input_object.get_data('input', '')
documents = knowledge.query_knowledge(query, top_k=5)
# Sync to context
if documents:
self._synchronizer.sync_knowledge_to_context(
knowledge_id=knowledge_name,
documents=[doc.text for doc in documents],
session_id=session_id,
priority=ContextPriority.HIGH
)
# Execute normally
return super().execute(input_object, agent_input)
```
### Pattern 3: Cross-Agent Context Sharing
**Use Case**: Multiple agents sharing context in a multi-agent system
**Implementation**:
```python
class AgentContextCoordinator:
"""Coordinates context sharing across multiple agents."""
def __init__(self, context_manager_name: str = "default_context_manager"):
self.context_manager = ContextManagerManager().get_instance_obj(
context_manager_name
)
self._shared_sessions = {} # agent_group_id -> session_id
def create_shared_session(self, agent_group_id: str) -> str:
"""Create a shared context session for a group of agents."""
session_id = f"shared_{agent_group_id}_{datetime.now().timestamp()}"
window = self.context_manager.create_context_window(
session_id=session_id,
task_type="dialogue"
)
self._shared_sessions[agent_group_id] = session_id
return session_id
def share_context(
self,
agent_group_id: str,
content: str,
source_agent: str,
context_type: ContextType = ContextType.CONVERSATION,
priority: ContextPriority = ContextPriority.MEDIUM
):
"""Share context from one agent to the group."""
session_id = self._shared_sessions.get(agent_group_id)
if not session_id:
session_id = self.create_shared_session(agent_group_id)
self.context_manager.add_context(
session_id,
content,
context_type,
priority,
metadata={
'source_agent': source_agent,
'shared': True,
'timestamp': datetime.now().isoformat()
}
)
def get_shared_context(
self,
agent_group_id: str,
context_type: Optional[ContextType] = None
) -> List[ContextSegment]:
"""Get shared context for the agent group."""
session_id = self._shared_sessions.get(agent_group_id)
if not session_id:
return []
return self.context_manager.get_context(
session_id,
context_type=context_type
)
# Usage
coordinator = AgentContextCoordinator()
# Create shared session for multiple agents
session_id = coordinator.create_shared_session("research_team")
# Agent 1 shares findings
coordinator.share_context(
agent_group_id="research_team",
content="Found relevant research paper on topic X",
source_agent="research_agent",
priority=ContextPriority.HIGH
)
# Agent 2 shares analysis
coordinator.share_context(
agent_group_id="research_team",
content="Analysis shows correlation with previous findings",
source_agent="analysis_agent",
priority=ContextPriority.HIGH
)
# Agent 3 retrieves all shared context
shared_context = coordinator.get_shared_context("research_team")
for segment in shared_context:
print(f"From {segment.metadata.custom['source_agent']}: {segment.content}")
```
### Pattern 4: Production Monitoring
**Implementation**:
```python
from dataclasses import dataclass
from typing import Dict, List
import time
@dataclass
class ContextMetrics:
"""Production metrics for context system."""
# Usage metrics
total_sessions: int = 0
active_sessions: int = 0
total_segments: int = 0
average_segments_per_session: float = 0.0
# Performance metrics
average_add_latency_ms: float = 0.0
average_search_latency_ms: float = 0.0
average_compression_latency_ms: float = 0.0
# Quality metrics
average_compression_ratio: float = 0.0
average_retrieval_precision: float = 0.0
# Resource metrics
total_memory_mb: float = 0.0
average_tokens_per_session: float = 0.0
class ContextMonitor:
"""Monitor context system performance in production."""
def __init__(self, context_manager_name: str = "default_context_manager"):
self.context_manager = ContextManagerManager().get_instance_obj(
context_manager_name
)
self._metrics_history: List[ContextMetrics] = []
self._operation_latencies: Dict[str, List[float]] = {
'add': [],
'search': [],
'compression': []
}
def track_operation(self, operation_type: str, latency_ms: float):
"""Track operation latency."""
if operation_type in self._operation_latencies:
self._operation_latencies[operation_type].append(latency_ms)
def collect_metrics(self) -> ContextMetrics:
"""Collect current metrics."""
import sys
metrics = ContextMetrics()
# Count active windows
if hasattr(self.context_manager, '_windows'):
metrics.total_sessions = len(self.context_manager._windows)
metrics.active_sessions = len([
w for w in self.context_manager._windows.values()
if w.total_tokens > 0
])
# Calculate average latencies
if self._operation_latencies['add']:
metrics.average_add_latency_ms = sum(self._operation_latencies['add']) / len(self._operation_latencies['add'])
if self._operation_latencies['search']:
metrics.average_search_latency_ms = sum(self._operation_latencies['search']) / len(self._operation_latencies['search'])
if self._operation_latencies['compression']:
metrics.average_compression_latency_ms = sum(self._operation_latencies['compression']) / len(self._operation_latencies['compression'])
# Memory usage
metrics.total_memory_mb = sys.getsizeof(self.context_manager) / (1024 * 1024)
self._metrics_history.append(metrics)
return metrics
def get_health_status(self) -> str:
"""Get system health status."""
metrics = self.collect_metrics()
# Check against targets
issues = []
if metrics.average_add_latency_ms > 100:
issues.append("High add latency")
if metrics.average_search_latency_ms > 100:
issues.append("High search latency")
if metrics.total_memory_mb > 500:
issues.append("High memory usage")
if not issues:
return "HEALTHY"
elif len(issues) <= 1:
return f"WARNING: {issues[0]}"
else:
return f"CRITICAL: {', '.join(issues)}"
def export_metrics(self) -> Dict[str, Any]:
"""Export metrics for monitoring system."""
metrics = self.collect_metrics()
return {
'timestamp': datetime.now().isoformat(),
'health_status': self.get_health_status(),
'metrics': {
'sessions': {
'total': metrics.total_sessions,
'active': metrics.active_sessions,
},
'performance': {
'add_latency_ms': metrics.average_add_latency_ms,
'search_latency_ms': metrics.average_search_latency_ms,
'compression_latency_ms': metrics.average_compression_latency_ms,
},
'resources': {
'memory_mb': metrics.total_memory_mb,
'average_tokens_per_session': metrics.average_tokens_per_session,
}
}
}
# Usage
monitor = ContextMonitor()
# Track operations
start = time.time()
context_manager.add_context(session_id, content, context_type, priority)
monitor.track_operation('add', (time.time() - start) * 1000)
# Collect metrics
metrics = monitor.collect_metrics()
print(f"Average add latency: {metrics.average_add_latency_ms:.1f}ms")
print(f"Memory usage: {metrics.total_memory_mb:.1f}MB")
print(f"Health: {monitor.get_health_status()}")
# Export for monitoring system
metrics_export = monitor.export_metrics()
# Send to Prometheus, DataDog, etc.
```
---
## Complete Example: Context-Aware Chat Agent
```python
# agent_context_chat.yaml
"""
name: 'context_chat_agent'
description: 'Context-aware chat agent with benchmarking'
profile:
llm_model:
name: 'gpt-4'
context_manager_name: 'default_context_manager'
task_type: 'dialogue'
system_prompt: |
You are a helpful assistant with excellent memory.
memory:
name: 'chat_memory'
plan:
planner:
name: 'react_planner'
"""
# Implementation
from agentuniverse.agent.default.default_agent import DefaultAgent
from agentuniverse.agent.context.benchmark.benchmark_suite import ContextBenchmarkSuite
class ContextChatAgent(DefaultAgent):
"""Production-ready context-aware chat agent."""
def __init__(self):
super().__init__()
self._context_manager = None
self._monitor = None
self._benchmark_suite = None
def initialize_by_component_configer(self, component_configer):
super().initialize_by_component_configer(component_configer)
# Initialize context manager
context_manager_name = self.agent_model.profile.get('context_manager_name')
if context_manager_name:
self._context_manager = ContextManagerManager().get_instance_obj(
context_manager_name
)
# Initialize monitor
self._monitor = ContextMonitor(context_manager_name)
# Initialize benchmark suite
self._benchmark_suite = ContextBenchmarkSuite(self._context_manager)
return self
def run(self, **kwargs):
"""Run with monitoring."""
import time
# Track operation
start = time.time()
result = super().run(**kwargs)
latency = (time.time() - start) * 1000
if self._monitor:
self._monitor.track_operation('run', latency)
return result
def run_benchmark(self, num_turns: int = 100):
"""Run benchmark evaluation."""
if not self._benchmark_suite:
raise ValueError("Benchmark suite not initialized")
result = self._benchmark_suite.run_full_suite(num_turns=num_turns)
return result
def get_health_metrics(self):
"""Get current health metrics."""
if not self._monitor:
return {}
return self._monitor.export_metrics()
# Usage
agent = AgentManager().get_instance_obj('context_chat_agent')
# Normal operation
output = agent.run(
input="What did we discuss yesterday?",
session_id="user_123"
)
# Get metrics
metrics = agent.get_health_metrics()
print(f"Health: {metrics['health_status']}")
# Run benchmark
benchmark_result = agent.run_benchmark(num_turns=50)
print(f"Score: {benchmark_result.metrics.get_score():.1f}/100")
print(f"Passes: {benchmark_result.metrics.passes_targets()}")
```
---
## Testing Phase 3-4 Features
### Test 1: Knowledge Synchronization
```python
def test_knowledge_sync():
"""Test knowledge-context synchronization."""
from agentuniverse.agent.context.sync.knowledge_context_synchronizer import (
KnowledgeContextSynchronizer,
ConflictResolutionStrategy
)
context_manager = ContextManagerManager().get_instance_obj("default_context_manager")
synchronizer = KnowledgeContextSynchronizer(context_manager)
# Test 1: Initial sync
result = synchronizer.sync_knowledge_to_context(
knowledge_id="test_doc",
documents=["Content version 1"],
session_id="test_session",
priority=ContextPriority.HIGH
)
assert result.segments_added == 1
assert result.segments_invalidated == 0
# Test 2: Update with no changes
result = synchronizer.sync_knowledge_to_context(
knowledge_id="test_doc",
documents=["Content version 1"], # Same content
session_id="test_session"
)
assert result.segments_added == 0 # No changes
# Test 3: Update with changes
result = synchronizer.sync_knowledge_to_context(
knowledge_id="test_doc",
documents=["Content version 2"], # Updated
session_id="test_session",
invalidate_old=True
)
assert result.segments_added == 1
assert result.segments_invalidated == 1
# Test 4: Version tracking
version = synchronizer.get_knowledge_version("test_doc")
assert version is not None
assert version.version_id.startswith("test_doc_")
print("✅ All knowledge sync tests passed")
test_knowledge_sync()
```
### Test 2: Benchmarking
```python
def test_benchmarking():
"""Test benchmark suite."""
from agentuniverse.agent.context.benchmark.benchmark_suite import (
ContextBenchmarkSuite
)
context_manager = ContextManagerManager().get_instance_obj("default_context_manager")
suite = ContextBenchmarkSuite(context_manager)
# Run full suite
result = suite.run_full_suite(num_turns=20) # Small for testing
# Check result structure
assert result.test_name == "full_suite"
assert result.metrics is not None
assert result.timestamp is not None
# Check metrics
metrics = result.metrics
assert 0 <= metrics.multi_turn_coherence <= 1
assert 0 <= metrics.compression_ratio <= 1
assert 0 <= metrics.information_loss <= 1
assert 0 <= metrics.retrieval_precision <= 1
assert metrics.average_latency_ms >= 0
assert metrics.memory_usage_mb >= 0
# Check scoring
score = metrics.get_score()
assert 0 <= score <= 100
print(f"✅ Benchmark test passed")
print(f" Score: {score:.1f}/100")
print(f" Coherence: {metrics.multi_turn_coherence:.3f}")
print(f" Compression: {metrics.compression_ratio:.1%}")
test_benchmarking()
```
---
## Production Deployment Checklist
### Configuration
- [ ] Set up context manager YAML with appropriate storage tiers
- [ ] Configure task-specific budgets for your use case
- [ ] Enable compression with appropriate strategy
- [ ] Set up monitoring and metrics collection
### Integration
- [ ] Integrate context manager with agents
- [ ] Set up knowledge synchronization if using knowledge base
- [ ] Implement cross-agent sharing if using multi-agent system
- [ ] Add monitoring to track performance
### Testing
- [ ] Run benchmark suite to validate performance
- [ ] Test knowledge synchronization with real data
- [ ] Verify compression quality and ratio
- [ ] Load test with production-scale data
### Monitoring
- [ ] Set up health checks and alerts
- [ ] Monitor latency metrics (add, search, compression)
- [ ] Track memory usage and resource consumption
- [ ] Set up benchmarking schedule (weekly/monthly)
---
## Performance Targets (vs Cursor/Claude)
| Metric | Target | Production Minimum |
|--------|--------|-------------------|
| Multi-turn coherence | >0.85 | >0.80 |
| Compression ratio | 60-80% | 50-80% |
| Information loss | <10% | <15% |
| Retrieval precision | >0.90 | >0.85 |
| Add latency | <50ms | <100ms |
| Search latency | <100ms | <200ms |
| Memory usage | <500MB | <750MB |
| Overall score | >85/100 | >75/100 |
---
## Troubleshooting
### Issue: Low coherence score
**Symptoms**: `multi_turn_coherence < 0.8`
**Solutions**:
- Increase compression quality threshold
- Use CRITICAL priority for important context
- Enable VERSION_BOTH conflict resolution
- Increase context window size
### Issue: High latency
**Symptoms**: `latency > 100ms`
**Solutions**:
- Enable caching in storage tier
- Use truncate compression for speed
- Reduce top_k in searches
- Optimize token counting
### Issue: Memory exhaustion
**Symptoms**: `memory_usage > 500MB`
**Solutions**:
- Enable warm/cold storage tiers
- Reduce TTL for ephemeral segments
- Increase compression aggressiveness
- Implement proactive pruning
---
## Next Steps
1. **Implement Integration**: Choose appropriate pattern for your use case
2. **Run Benchmarks**: Validate performance against targets
3. **Deploy to Staging**: Test with production-like load
4. **Monitor Metrics**: Track performance and quality metrics
5. **Optimize**: Tune configuration based on metrics
6. **Scale**: Deploy to production with monitoring
---
## Support
For issues or questions:
- Review Phase 2 test results: `PHASE2_最终测试报告.md`
- Check implementation details in source files
- Run benchmark suite for diagnostics
- Monitor production metrics for insights
**Phase 3-4 Status**: ✅ Complete with integration patterns ready for production use.
+461
View File
@@ -0,0 +1,461 @@
# 上下文工程系统 - 快速开始指南
## Context Engineering System - Quick Start Guide
**5 分钟上手 agentUniverse 上下文管理系统**
---
## 📦 什么是上下文工程系统?
上下文工程系统为 agentUniverse Agent 提供:
- ✅ 智能上下文管理(自动压缩、多层存储)
- ✅ 长对话记忆(跨会话保持连贯性)
- ✅ 知识库同步(自动更新、冲突解决)
- ✅ 性能监控(延迟、内存、质量指标)
**对标**: Cursor、Claude 等行业领先产品
---
## 🚀 快速开始
### 步骤 1: 基本使用(2 分钟)
```python
# 1. 导入必要的类
from agentuniverse.agent.context.context_manager_manager import ContextManagerManager
from agentuniverse.agent.context.context_model import ContextType, ContextPriority
# 2. 获取上下文管理器实例
context_manager = ContextManagerManager().get_instance_obj("default_context_manager")
# 3. 创建上下文窗口(每个会话一个)
window = context_manager.create_context_window(
session_id="user_123",
task_type="dialogue" # 可选: code_generation, data_analysis
)
# 4. 添加用户输入
context_manager.add_context(
session_id="user_123",
content="今天天气怎么样?",
context_type=ContextType.CONVERSATION,
priority=ContextPriority.HIGH
)
# 5. 添加 Agent 回复
context_manager.add_context(
session_id="user_123",
content="今天天气晴朗,温度 20°C。",
context_type=ContextType.CONVERSATION,
priority=ContextPriority.HIGH
)
# 6. 下一轮对话,搜索相关上下文
results = context_manager.search_context(
session_id="user_123",
query="天气",
top_k=5
)
for segment in results:
print(f"[{segment.priority}] {segment.content}")
# 7. 查看 token 使用情况
metrics = context_manager.get_budget_utilization("user_123")
print(f"Token 使用率: {metrics['utilization']:.1%}")
print(f"总 tokens: {metrics['total_tokens']}")
```
**就是这么简单!** 系统会自动处理压缩、存储和检索。
---
### 步骤 2: 知识同步(可选,3 分钟)
如果你的 Agent 使用知识库,可以自动同步知识到上下文:
```python
from agentuniverse.agent.context.sync.knowledge_context_synchronizer import (
KnowledgeContextSynchronizer,
ConflictResolutionStrategy
)
# 1. 创建同步器
synchronizer = KnowledgeContextSynchronizer(
context_manager=context_manager,
conflict_strategy=ConflictResolutionStrategy.NEWEST_WINS
)
# 2. 同步知识文档到上下文
result = synchronizer.sync_knowledge_to_context(
knowledge_id="user_manual",
documents=[
"产品特性:支持多种文件格式...",
"安装步骤:1. 下载安装包 2. 运行安装..."
],
session_id="user_123",
priority=ContextPriority.HIGH
)
print(f"✅ 添加了 {result.segments_added} 个知识片段")
# 3. 更新知识(内容变化时自动检测)
result = synchronizer.sync_knowledge_to_context(
knowledge_id="user_manual",
documents=["产品特性:新增 PDF 导出功能..."], # 更新后的内容
session_id="user_123"
)
print(f"✅ 更新了知识,失效了 {result.segments_invalidated} 个旧片段")
```
---
### 步骤 3: 运行基准测试(可选,1 分钟)
验证系统性能:
```python
from agentuniverse.agent.context.benchmark.benchmark_suite import (
ContextBenchmarkSuite
)
# 1. 创建基准测试套件
suite = ContextBenchmarkSuite(context_manager)
# 2. 运行测试(100 轮对话模拟)
result = suite.run_full_suite(num_turns=100)
# 3. 查看结果
print(f"📊 整体评分: {result.metrics.get_score():.1f}/100")
print(f"✅ 通过所有目标: {result.metrics.passes_targets()}")
print(f" - 多轮连贯性: {result.metrics.multi_turn_coherence:.3f}")
print(f" - 压缩率: {result.metrics.compression_ratio:.1%}")
print(f" - 检索精确度: {result.metrics.retrieval_precision:.3f}")
```
**目标**: 评分 >85/100,所有指标达到行业标准。
---
## 🎯 三种使用场景
### 场景 1: 简单对话机器人
**需求**: 记住最近的对话,提供连贯的回复
**配置**: 默认配置即可
**代码**:
```python
# 每次用户输入
context_manager.add_context(session_id, user_input, ContextType.CONVERSATION, ContextPriority.HIGH)
# 每次 Agent 回复
context_manager.add_context(session_id, agent_output, ContextType.CONVERSATION, ContextPriority.HIGH)
# 系统自动处理上下文压缩和检索
```
---
### 场景 2: 知识问答系统
**需求**: 基于知识库回答问题,知识更新时自动同步
**配置**: 启用知识同步
**代码**:
```python
# 初始化同步器
synchronizer = KnowledgeContextSynchronizer(context_manager)
# 每次查询前同步相关知识
documents = knowledge_base.query(user_question, top_k=5)
synchronizer.sync_knowledge_to_context(
knowledge_id="kb_v1",
documents=[doc.text for doc in documents],
session_id=session_id
)
# 使用上下文生成回答
context = context_manager.get_context(session_id)
agent_answer = llm.generate(context + user_question)
```
---
### 场景 3: 多 Agent 协作系统
**需求**: 多个 Agent 共享上下文,协同完成任务
**配置**: 使用 AgentContextCoordinator
**代码**:
```python
from agentuniverse.agent.context.sync.knowledge_context_synchronizer import (
AgentContextCoordinator # 见 PHASE3_4_INTEGRATION_GUIDE.md
)
# 创建协调器
coordinator = AgentContextCoordinator()
# 创建共享会话
session_id = coordinator.create_shared_session("research_team")
# Agent 1 分享发现
coordinator.share_context(
agent_group_id="research_team",
content="找到相关论文: ...",
source_agent="research_agent"
)
# Agent 2 获取共享上下文
shared_context = coordinator.get_shared_context("research_team")
```
---
## 📋 配置说明
### 最小配置(使用默认)
系统开箱即用,默认配置已优化:
- 热存储: RAM (快速访问)
- 压缩策略: Adaptive (自适应选择)
- Token 预算: 8000 (对话), 10000 (代码), 12000 (分析)
### 自定义配置(可选)
创建 `config/context_manager/my_context_manager.yaml`:
```yaml
name: 'my_context_manager'
hot_store_name: 'ram_context_store'
warm_store_name: 'redis_context_store' # 可选: 持久化
cold_store_name: 'chroma_context_store' # 可选: 长期存储
llm_name: 'gpt-4'
default_max_tokens: 10000
enable_compression: true
metadata:
type: 'CONTEXT_MANAGER'
module: 'agentuniverse.agent.context.context_manager'
class: 'ContextManager'
```
---
## 🎓 进阶主题
### 压缩策略选择
系统提供 5 种压缩策略:
| 策略 | 速度 | 质量 | 适用场景 |
|------|------|------|----------|
| Truncate | 最快 | 一般 | 实时对话 |
| Selective | 快 | 好 | 一般应用 ⭐ |
| Summarize | 慢 | 最好 | 高质量要求 |
| Hybrid | 中等 | 好 | 平衡场景 |
| Adaptive | 自动 | 自动 | 推荐默认 ⭐ |
**推荐**: 使用 `Adaptive`(默认),系统自动选择最优策略。
### 优先级管理
5 种优先级:
| 优先级 | 说明 | 何时使用 |
|--------|------|----------|
| CRITICAL | 永不压缩 | 系统提示、核心指令 |
| HIGH | 优先保留 | 重要对话、关键知识 |
| MEDIUM | 按需保留 | 一般内容 |
| LOW | 容易压缩 | 背景信息 |
| EPHEMERAL | 立即丢弃 | 临时数据 |
**最佳实践**:
- 系统提示 → CRITICAL
- 用户输入 → HIGH
- Agent 回复 → HIGH
- 背景知识 → MEDIUM
- 临时计算 → EPHEMERAL
### 任务类型配置
系统支持 3 种预配置任务类型:
**1. dialogue (对话)**
- Token 预算: 8000
- 侧重: 对话历史 (50%)
**2. code_generation (代码生成)**
- Token 预算: 10000
- 侧重: 代码文件 (50%)
**3. data_analysis (数据分析)**
- Token 预算: 12000
- 侧重: 数据上下文 (40%)
创建上下文窗口时指定:
```python
window = context_manager.create_context_window(
session_id="session_123",
task_type="code_generation" # 自动使用代码生成配置
)
```
---
## 🐛 常见问题
### Q1: 上下文太长,压缩不够?
**解决**: 调整压缩率或使用更激进的策略
```python
# 手动触发压缩
from agentuniverse.agent.context.compressor.adaptive_compressor import AdaptiveCompressor
compressor = AdaptiveCompressor(
name="aggressive_compressor",
llm_name="gpt-4",
compression_ratio=0.4, # 60% 压缩
enable_hybrid=True
)
# 或者降低 token 预算
window = context_manager.create_context_window(
session_id="session_123",
max_tokens=6000 # 从 8000 降到 6000
)
```
### Q2: 检索不准确?
**解决**: 使用更具体的查询词,或增加 top_k
```python
# 更具体的查询
results = context_manager.search_context(
session_id="session_123",
query="用户关于产品价格的问题", # 而不是 "价格"
top_k=10 # 增加返回数量
)
# 按类型过滤
conversation_context = context_manager.get_context(
session_id="session_123",
context_type=ContextType.CONVERSATION # 只获取对话
)
```
### Q3: 内存占用太高?
**解决**: 启用多层存储,将旧上下文移到 Redis/Chroma
```yaml
# config/context_manager/my_context_manager.yaml
warm_store_name: 'redis_context_store' # 启用 Redis
cold_store_name: 'chroma_context_store' # 启用向量数据库
```
系统会自动将不常用的上下文移到暖/冷存储。
### Q4: 需要更详细的监控?
**解决**: 使用 ContextMonitor
```python
from agentuniverse.agent.context.benchmark.benchmark_suite import (
ContextMonitor # 见 PHASE3_4_INTEGRATION_GUIDE.md
)
monitor = ContextMonitor(context_manager_name="default_context_manager")
# 收集指标
metrics = monitor.collect_metrics()
print(f"活跃会话: {metrics.active_sessions}")
print(f"平均延迟: {metrics.average_add_latency_ms:.1f}ms")
print(f"内存使用: {metrics.total_memory_mb:.1f}MB")
# 健康检查
health = monitor.get_health_status()
print(f"系统健康: {health}") # HEALTHY, WARNING, CRITICAL
```
---
## 📚 完整文档
- **集成指南**: `PHASE3_4_INTEGRATION_GUIDE.md` (850+ 行)
- 5 种 Agent 集成模式详解
- 完整代码示例
- 生产部署指南
- **测试报告**: `PHASE2_最终测试报告.md`
- 30 个单元测试详解
- 性能验证结果
- **项目总结**: `阶段总结.md`
- 完整项目概览
- 所有组件说明
---
## 🎯 下一步
1. ✅ **试用基本功能**: 运行上面的快速开始代码
2. ✅ **运行基准测试**: 验证系统性能
3. ✅ **查看集成指南**: 选择适合的集成模式
4. ⏳ **集成到你的 Agent**: 按照指南集成
5. ⏳ **部署到生产**: 使用监控系统跟踪性能
---
## 💡 最佳实践
1. **永远使用 CRITICAL 优先级存储系统提示**
2. **为不同任务使用不同的 task_type**
3. **定期运行基准测试验证性能**
4. **启用监控跟踪生产环境指标**
5. **使用知识同步保持知识库最新**
---
## 🚀 开始使用
```python
# 最简单的完整示例
from agentuniverse.agent.context.context_manager_manager import ContextManagerManager
from agentuniverse.agent.context.context_model import ContextType, ContextPriority
# 1. 获取管理器
cm = ContextManagerManager().get_instance_obj("default_context_manager")
# 2. 创建会话
cm.create_context_window(session_id="user_123", task_type="dialogue")
# 3. 添加对话
cm.add_context("user_123", "你好!", ContextType.CONVERSATION, ContextPriority.HIGH)
cm.add_context("user_123", "你好!有什么可以帮助你的吗?", ContextType.CONVERSATION, ContextPriority.HIGH)
# 4. 查询上下文
results = cm.search_context("user_123", "帮助", top_k=5)
for r in results:
print(r.content)
# 5. 查看使用情况
metrics = cm.get_budget_utilization("user_123")
print(f"使用率: {metrics['utilization']:.1%}")
```
**就这么简单!开始构建你的上下文感知 Agent 吧!** 🎉
---
**需要帮助?** 查看完整文档:
- `PHASE3_4_INTEGRATION_GUIDE.md` - 详细集成指南
- `阶段总结.md` - 完整项目说明
- `PHASE2_最终测试报告.md` - 性能验证报告
+225
View File
@@ -0,0 +1,225 @@
# agentUniverse
****************************************
Language version: [English](./README.md) | [中文](./README_zh.md) | [日本語](./README_jp.md)
![](https://img.shields.io/badge/framework-agentUniverse-pink)
![](https://img.shields.io/badge/python-3.10%2B-blue?logo=Python)
[![](https://img.shields.io/badge/%20license-Apache--2.0-yellow)](LICENSE)
[![Static Badge](https://img.shields.io/badge/pypi-v0.0.19-blue?logo=pypi)](https://pypi.org/project/agentUniverse/)
![](docs/guidebook/_picture/logo_bar.jpg)
****************************************
## What is agentUniverse?
**agentUniverse is a multi-agent framework based on large language models.** It provides flexible and easily extensible capabilities for building individual agents. The core of agentUniverse is a rich set of multi-agent collaborative pattern components (serving as a collaborative pattern factory), which allows agents to perform their respective duties and maximize their capabilities when solving problems in different fields; at the same time, agentUniverse focuses on the integration of domain experience, helping you smoothly integrate domain experience into the work of intelligent agents.🎉🎉🎉
**🌈🌈🌈agentUniverse originates from the real-world financial business practices of AntGroup (https://github.com/antgroup), dedicated to assisting developers and enterprises in effortlessly constructing domain-expert-level intelligent agents that collaborate to accomplish tasks.**
![](docs/guidebook/_picture/agent_universe_framework_resize.jpg)
We look forward to your practice and communication and sharing of Patterns in different fields through the community. This framework has already placed many useful components that have been tested in real business scenarios in terms of multi-agent cooperation, and will continue to be enriched in the future.
The pattern components that are currently open for use include:
* PEER pattern component: This pattern uses agents with different responsibilities—Plan, Execute, Express, and Review—to break down complex problems into manageable steps, execute the steps in sequence, and iteratively improve based on feedback, enhancing the performance of reasoning and analysis tasks. Typical use cases: Event interpretation, industry analysis.
* DOE pattern component: This pattern employs three agents—Data-fining, Opinion-inject, and Express—to improve the effectiveness of tasks that are data-intensive, require high computational precision, and incorporate expert opinions. Typical use cases: Financial report generation.
More patterns are coming soon...
The LLM model integration can be accomplished with simple configuration, currently agentUniverse supported models include:
|-|Vendors| Models |
|:-----:|:--------:|:-----------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------:|
|<img src="https://github.com/user-attachments/assets/b7b0f2ce-3250-4008-b6d7-4712a983deb9" height="25">|Qwen| qwen3 Series(qwen3-235b-a22b、qwen3-32b、qwen3-30b-a3b, etc.) 、qwen2.5-72b-instruct、qwq-32b-preview、qwen-max、… |
|<img src="https://github.com/user-attachments/assets/5a997feb-bef4-4e53-ac3e-d38221e5399c" height="25">|Deepseek| deepseek-r1、deepseek-v3、deepseek-r1-distill-qwen-32b、… |
|<img src="https://github.com/user-attachments/assets/0b50e555-65e8-49b2-b725-f3f71ee7daed" height="25">|OpenAI| GPT-4o、GPT-4o mini、OpenAI o1、OpenAI o3-mini、… |
|<img src="https://github.com/user-attachments/assets/60fe0a70-0b47-4ac7-9bc9-8e860732ace9" height="25">|Claude| claude 3.7 sonnet 、Claude 3.5 Sonnet、Claude 3 Opus、… |
|<img src="https://github.com/user-attachments/assets/334c7f09-7eae-4a65-a70f-2e6531964224" height="25">|Gemini| Gemini 2.5 Pro、Gemini 2.0 Flash、Gemini 2.0 Flash Thinking、Gemini 1.5 Pro、… |
|<img src="https://github.com/user-attachments/assets/8e41c73f-3103-4305-ad1f-56116ea55523" height="25">|Llama| llama3.3-70b-instruct、llama3.2-3b-instruct、llama3.2-1b-instruct、… |
|<img src="https://github.com/user-attachments/assets/19d264c6-e499-4913-9d6d-314d392f2246" height="25">|KIMI| moonshot-v1-128k、moonshot-v1-32k、moonshot-v1-8k、… |
|<img src="https://github.com/user-attachments/assets/79572d9a-29d5-4c0e-a336-ce3f8018fb05" height="25">|WenXin| ERNIE 4.5 Turbo、ERNIE 4.5、ERNIE 4.0 Turbo、ERNIE 4.0、ERNIE 3.5、… |
|<img src="https://github.com/user-attachments/assets/abb5311e-4d70-4e9c-8fca-e5129ae912fc" height="25">|chatglm| chatglm3-6b、chatglm-6b-v2、… |
|<img src="https://github.com/user-attachments/assets/fe265f24-4ea6-4ff2-9b50-58ab6706a5f5" height="25">|BaiChuan| baichuan2-turbo、baichuan2-13b-chat-v1、… |
|<img src="https://github.com/user-attachments/assets/41ffe268-392f-4ab9-b42d-e30dbd70d66b" height="25">|Doubao| Doubao-pro-128k、Doubao-pro-32k、Doubao-lite-128k、… |
For example, to use deepseek model, you can simply set DEEPSEEK_API_KEY value in the custom_key.toml file, and set the llm_model name in the agent configuration file to 'default_deepseek_llm' and you're all set. For more information about llm configuration, please refer to [switch-the-llm](https://github.com/agentuniverse-ai/agentUniverse/blob/master/docs/guidebook/en/Get_Start/2.Run_Your_First_Tutorial_Example.md#switch-the-llm).
****************************************
## Table of Contents
* [Quick Start](#Quick-Start)
* [How to build an agent application](#How-to-build-an-agent-application)
* [Setup the visual agentic workflow platform](#Set-up-the-visual-agentic-workflow-platform)
* [Why use agentUniverse](#Why-use-agentUniverse)
* [Sample Apps](#Sample-Apps)
* [Documents](#Documents)
* [Support](#Support)
****************************************
## Quick Start
### Installation
Using pip:
```shell
pip install agentUniverse
```
### Run the first example
Run your first example, and you can quickly experience the performance of the agents (or agent groups) built by agentUniverse through the tutorial.
Please refer to the document for detail steps: [Run the first example](docs/guidebook/en/Get_Start/2.Run_Your_First_Tutorial_Example.md) 。
****************************************
## How to build an agent application
### Standard Project Scaffolding
Setup the standard project: [agentUniverse Standard Project](examples/sample_standard_app)
#### Quick Start for Building a Single Agent
You can learn how to quickly build a single agent by reading the [Quick Guide to Build Single Agent](docs/guidebook/en/Get_Start/3.Quick_Guide_to_Build_Single_Agent.md). This will help you understand how to enhance your agent's capabilities using tools, knowledge bases, RAG technologies, and more. Additionally, you will grasp the basic application development processes for agents, including configuration, testing, optimizing, deployment, and performance evaluation.
#### Building Typical Multi-Agent Applications
You can further understand how to break down intelligent capabilities into multiple agents in complex task scenarios and enhance your task performance through collaboration by referring to the [Building Typical Multi-Agent App](docs/guidebook/en/Get_Start/4.Building_Typical_Multi-Agent_App.md) chapter.
#### Creating and Using Agent Templates
You can learn how to create effective agent patterns into templates through the chapter [Creating and Using Agent Templates](docs/guidebook/en/Get_Start/5.Creating_and_Using_Agent_Templates.md). This will greatly enhance the efficiency of constructing subsequent agents and facilitate dissemination.
#### Using and Publishing MCP Servers
You can learn how to quickly use or publish MCP servers in agentUniverse framework by referring to [How to Use MCP Servers](docs/guidebook/en/How-to/Use%20and%20Publish%20MCP%20Server/How_to_Use_MCP_Servers.md) and [How to Publish MCP Servers](docs/guidebook/en/How-to/Use%20and%20Publish%20MCP%20Server/How_to_Publish_MCP_Servers.md).
#### Agent Application Observability
agentUniverse provides a standardized observability framework for agent applications. Based on the OpenTelemetry protocol, it enables comprehensive data collection and monitoring of critical components such as agents, LLMs, and tools, facilitating full lifecycle tracking of agents. You can learn how to utilize these observability capabilities in the [Agent Application Observability](docs/guidebook/en/In-Depth_Guides/Tech_Capabilities/Observability/Observability_with_OTEL.md) section.
#### Common Tips and Advanced Techniques
You can learn more advanced techniques in the agent application building process through other documents in the [Get_Start](./docs/guidebook/en/Get_Start), such as how to add a memory module into the intelligent agent process and how to effectively manage prompts within the project.
****************************************
## Set up the visual agentic workflow platform
agentUniverse provides a visual canvas platform for creating agentic workflow. Follow these steps for a quick start:
**Using pip**
```shell
pip install magent-ui ruamel.yaml
```
**One-click Run**
Run [product_application.py](examples/sample_apps/workflow_agent_app/bootstrap/platform/product_application.py) in sample_apps/workflow_agent_app/bootstrap/platform for quick startup.
For more details, refer to [Quick Start for Product Platform](docs/guidebook/en/How-to/Guide to Visual Agentic Workflow Platform/Product_Platform_Quick_Start.md) and the [Advanced Guide](docs/guidebook/en/How-to/Guide to Visual Agentic Workflow Platform/Product_Platform_Advancement_Guide.md).
This feature is jointly developed by [difizen](https://github.com/difizen/magent) and agentUniverse.
****************************************
## Why use agentUniverse
### Concept
![](docs/guidebook/_picture/agentuniverse_structure_en.png)
The core of agentUniverse provides all the essential components needed to build a single intelligent agent, the collaboration mechanisms between multiple agents, and allows for the injection of expert knowledge. The enables developers to effortlessly create intelligent applications equipped with professional know-how.
### Multi Agent Collaboration
agentUniverse offers several multi-agent collaboration model components that have been validated in real-world industries. Among these, the "PEER" model stands out as one of the most distinctive.
The PEER model utilizes agents with four distinct responsibilities: Planning, Executing, Expressing, and Reviewing. This structure allows for the decomposition and step-by-step execution of complex problems and enables autonomous iteration based on evaluation feedback, ultimately enhancing performance in reasoning and analytical tasks. This model is particularly effective in scenarios that require multi-step decomposition and in-depth analysis, such as event interpretation, macroeconomic analysis, and the feasibility analysis of business proposals.
The PEER model has achieved impressive results, and the latest research findings and experimental data can be found in the following literature.
### Key Features
Based on the above introduction, we summarize the main features of agentUniverse as follow:
Flexible and Extensible Agent Construction Capability: It provides all the essential components necessary for building agents, all of which support customization to tailor user-specific agents.
Rich and Effective Multi-Agent Collaboration Models: It offers collaborative models such as PEER (Plan/Execute/Express/Review) and DOE (Data-finding/Opinion-inject/Express), which have been validated in the industry. Users can also customize and orchestrate new models to facilitate organic collaboration among multiple agents.
Easy Integration of Domain Expertise: It offers capabilities for domain prompts, knowledge construction, and management, enabling the orchestration and injection of domain-level SOPs, aligning agents with expert-level domain knowledge.
💡 For additional features:
see the section on [key features of agentUniverse](docs/guidebook/en/Concepts/Core_Features.md) for more details.
****************************************
## Sample Apps
🚩 [Legal Advice Agent v2](docs/guidebook/en/Examples/Legal_Advice.md)
🚩 [Python Code Generation and Execution Agent](docs/guidebook/en/Examples/Python_Auto_Runner.md)
🚩 [Discussion Group Based on Multi-Turn Multi-Agent Mode](docs/guidebook/en/Examples/Discussion_Group.md)
🚩 [Financial Event Analysis Based on PEER Multi-Agent Mode](docs/guidebook/en/Examples/Financial_Event_Analysis.md)
🚩 [Andrew Ng's Reflexive Workflow Translation Agent Replication](docs/guidebook/en/Examples/Translation_Assistant.md)
****************************************
## Commercial Product base on agentUniverse
🔗 [_Zhi Xiao Zhu_-AI Assistant for Financial Professionals](https://zhu.alipay.com/?from=au)
**_Zhi Xiao Zhu_ AI Assistant: Designed to facilitate the development of large models in rigorous industries to enhance the productively of investment research experts**
_Zhi Xiao Zhu_ AI Assistant an efficient solution for the practical application of large models in rigorous industries. It is built upon the Finix model, which emphasizes precise applications, and leverages the agentUniverse intelligent agent framework, known for its professional customization capabilities. This solution targets a range of professional AI business assistants related to investment research, ESG (environmental, social, and governance), finance, earnings reports, and other specialized domains. It has been extensively validated in large-scale scenarios at Ant Group, significantly improving expert efficiency.
https://private-user-images.githubusercontent.com/39180831/355437700-192f712d-1b03-46a6-8422-1ca10aa94331.mp4?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MjI5NDk4NTAsIm5iZiI6MTcyMjk0OTU1MCwicGF0aCI6Ii8zOTE4MDgzMS8zNTU0Mzc3MDAtMTkyZjcxMmQtMWIwMy00NmE2LTg0MjItMWNhMTBhYTk0MzMxLm1wND9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNDA4MDYlMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjQwODA2VDEzMDU1MFomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTU4NWMzNzVjOGZjZDNjMDMzMTE4YjQzOTk0ZWQwZGZkNWNmNWQxNWMzYWIzMTk4MzY1MjA5NWRhMjU2NGNiNzUmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JmFjdG9yX2lkPTAma2V5X2lkPTAmcmVwb19pZD0wIn0.q1vdSg_Ghxr-DHLXfmQ_fVVRVSFn7H8VMHMi-_2QrjA
****************************************
## Documents
### User Guide
💡 For more detailed information, please refer to the [User Guide](./docs/guidebook/en/Contents.md).
### API Reference
💡 Please consult the [API Reference](https://agentuniverse.readthedocs.io/en/latest/) for technical details.
****************************************
## Support
### Submit Questions via GitHub Issues
😊 We recommend submitting your queries using [GitHub Issues](https://github.com/agentuniverse-ai/agentUniverse/issues), we typically respond within 2 business days.
### Contact Us via Discord
😊 Join our [Discord Channel](https://discord.gg/DHFcdkWAhn) to interact with us.
### Contact Us via Administrator Email
😊 Email:
* [jihan.hanji@antgroup.com](mailto:jihan.hanji@antgroup.com)
* [jerry.zzw@antgroup.com](mailto:jerry.zzw@antgroup.com)
* [jinshi.zjs@antgroup.com](mailto:jinshi.zjs@antgroup.com)
### twitter
ID: [@agentuniverse_](https://x.com/agentuniverse_)
****************************************
## Citation
The PEER multi-agent framework build in agentUniverse project is supported by the following research achievements.
BibTeX formatted
```text
@misc{wang2024peerexpertizingdomainspecifictasks,
title={PEER: Expertizing Domain-Specific Tasks with a Multi-Agent Framework and Tuning Methods},
author={Yiying Wang and Xiaojing Li and Binzhu Wang and Yueyang Zhou and Han Ji and Hong Chen and Jinshi Zhang and Fei Yu and Zewei Zhao and Song Jin and Renji Gong and Wanqing Xu},
year={2024},
eprint={2407.06985},
archivePrefix={arXiv},
primaryClass={cs.AI},
url={https://arxiv.org/abs/2407.06985},
}
```
Overview: This document introduces in detailed the mechanisms and principles underlying the PEER multi-agent framework. The experimental section assigned scores across seven dimensions: completeness, relevance, conciseness, factualness, logicality, structure, and comprehensiveness, with a maximum score of 5 points for each dimension. On average, the PEER model scored higher in each evaluation dimension compared to BabyAGI, and show notable advantages particularly in completeness, relevance, logicality, structure, and comprehensiveness. Furthermore, when tested with the GPT-3.5 Turbo (16k) model, the PEER model achieved a superior accuracy rate of 83% compared to BabyAGI, and with the GPT-4 model, it achieved an accuracy rate of 81%. For more details, please refer to the document.
🔗https://arxiv.org/pdf/2407.06985
****************************************
### Acknowledgements
This project is partially built upon excellent open-source projects such as Langchain, Pydantic, Gunicorn, Flask, SQLAlchemy, chromadb, etc. (The detailed dependency list can be found in pyproject.toml). We would like to express our heartfelt gratitude to the related projects and their contributors. 🙏🙏🙏
+15
View File
@@ -0,0 +1,15 @@
# agentUniverse
## Overview
agentUniverse is a framework for developing applications powered by multi-agent base on large language model. It provides all the essential components for building a single agent, and a multi-agent collaboration mechanism which serves as a pattern factory that allowing developers to build and customize multi-agent collaboration patterns. With this framework, developers can easily construct multi-agent applications, and share the pattern practices from different technical and business fields.
The framework will come with several pre-install multi-agent collaboration patterns which have been proven effective in real business scenarios, and will continue to be enriched in the future. Patterns that are currently about to be released include:
- PEER pattern:
This pattern utilizes four distinct agent roles: Plan, Execute, Express, and Review, to achieve a multi-step breakdown and sequential execution of a complex task. It also performs autonomous iteration based on evaluative feedback which enhancing performance in reasoning and analytical tasks.
- DOE pattern:
This pattern consists of three agents: Data-fining agent, which is designed to solve data-intensive and high-computational-precision task; Opinion-inject agent, which combines the data results from first agent and the expert opinions which are pre-collected and structured; the third agent, Express agent generates the final result base on given document type and language style.
More patterns are coming soon...
+171
View File
@@ -0,0 +1,171 @@
# agentUniverse
****************************************
言語バージョン: [英語](./README.md) | [中国語](./README_zh.md) | [日本語](./README_jp.md)
![](https://img.shields.io/badge/framework-agentUniverse-pink)
![](https://img.shields.io/badge/python-3.10%2B-blue?logo=Python)
[![](https://img.shields.io/badge/%20license-Apache--2.0-yellow)](LICENSE)
[![Static Badge](https://img.shields.io/badge/pypi-v0.0.19-blue?logo=pypi)](https://pypi.org/project/agentUniverse/)
![](docs/guidebook/_picture/logo_bar.jpg)
****************************************
## agentUniverseとは何ですか?
**agentUniverseは、大型言語モデルに基づくマルチエージェントフレームワークです。** agentUniverseは、柔軟で拡張性のある単一エージェント構築能力を提供します。agentUniverseのコアには、多様なマルチエージェント協調モデルコンポーネントが豊富に揃っており(協調モデル工場として考えることができます)、エージェントがそれぞれの役割を果たしながら、異なる分野の問題を解決する際に最大の能力を発揮できるようにします。また、agentUniverseは分野の経験の融合に注力し、容易にその経験をエージェントの業務に取り入れる手助けをします。🎉🎉🎉
**🌈🌈🌈agentUniverseは、開発者や企業が専門家レベルの強力なエージェントを簡単に構築し、協力して働くことを支援します。**
![](docs/guidebook/_picture/agent_universe_framework_resize.jpg)
フレームワークには、実際のビジネスシナリオで効果が証明されたいくつかのプリインストールされたマルチエージェントコラボレーションパターンが含まれており、今後も豊富になる予定です。現在リリース予定のパターンには以下が含まれます:
PEERパターン: このパターンは、Plan(計画)、Execute(実行)、Express(表現)、Review(レビュー)の4つの異なるエージェントの役割を利用して、複雑なタスクを多段階に分解し、順次実行します。また、評価フィードバックに基づいて自律的な反復を行い、推論および分析タスクのパフォーマンスを向上させます。
DOEパターン: このパターンは、Data-fining(データ精製)、Opinion-inject(意見注入)、Express(表現)の3つのエージェントで構成され、データ集約型および高計算精度のタスクを解決し、事前に収集および構造化された専門家の意見と組み合わせることで、最終結果を生成します。
これからもっと多くのパターンが登場します...
****************************************
## 目録
* [クイックスタート](#クイックスタート)
* [インテリジェントエージェントアプリケーションの構築方法](#インテリジェントエージェントアプリケーションの構築方法)
* [キャンバス式開発プラットフォームの構築](#キャンバス式開発プラットフォームの構築)
* [なぜエージェントユニバースを使用するのか](#なぜエージェントユニバースを使用するのか)
* [サンプルアプリ](#サンプルアプリ)
* [文書資料](#文書資料)
* [サポート](#サポート)
****************************************
## クイックスタート
### クイックインストール
pipを使用:
```shell
pip install agentUniverse
```
### 最初のチュートリアルケースを実行する
あなたの最初のケースを実行することで、チュートリアルを通じてagentUniverseによって構築されたエージェント(グループ)の動作をすぐに体験できます。
詳細な手順については、ドキュメントを参照してください: [最初のチュートリアルケースを実行する](docs/guidebook/en/Get_Start/2.Run_Your_First_Tutorial_Example.md) 。
****************************************
## インテリジェントエージェントアプリケーションの構築方法
### agentUniverseサンプルプロジェクト
⌨️ agentUniverseサンプルプロジェクト: [agentUniverse Standard Project](examples/sample_standard_app)
#### 単体知能エージェントの迅速構築
[単体のインテリジェントエージェントを迅速に構築する](docs/guidebook/en/Get_Start/3.Quick_Guide_to_Build_Single_Agent.md)の章を読むことで、単一のインテリジェントエージェントを迅速に構築する方法を理解し、ツール、知識ベース、RAG技術などの能力を活用してインテリジェントエージェントの能力を強化する方法を習得できます。また、インテリジェントエージェントの設定、テスト、調整、サービス化、効果評価など、一連の基本的なインテリジェントエージェントアプリケーションの開発プロセスも学ぶことができます。
#### 典型的なマルチエージェントアプリケーションの構築
複雑なタスクシナリオにおいて、エージェントの能力を複数のエージェントに分割し、協力してタスクのパフォーマンスを向上させる方法については、[典型的なマルチエージェントアプリケーションの構築](docs/guidebook/en/Get_Start/4.Building_Typical_Multi-Agent_App.md)章を通じてさらに学ぶことができます。
#### 智能体テンプレートの構築と使用
効果的なエージェントのパターンをテンプレートとして確立し、使用する方法については、[エージェントテンプレートの構築と使用](docs/guidebook/en/Get_Start/5.Creating_and_Using_Agent_Templates.md)の章をご覧ください。これにより、今後のエージェントの構築効率が大幅に向上し、共有が容易になります。
#### MCP サービスの利用と公開
agentUniverse フレームワークでMCPサービスを迅速に利用または公開する方法は、以下のドキュメントを参照してください: [MCPサーバーの利用方法](docs/guidebook/en/How-to/Use%20and%20Publish%20MCP%20Server/How_to_Use_MCP_Servers.md) 、 [MCPサーバーの公開方法](docs/guidebook/en/How-to/Use%20and%20Publish%20MCP%20Server/How_to_Publish_MCP_Servers.md).
#### よく使われる利用技術
[一般的な使用のコツ](docs/guidebook/en/Get_Start)セクションを通じて、スマートエージェントアプリケーションの構築プロセスにおける一般的なテクニックを理解できます。たとえば、スマートエージェントプロセスにメモリモジュールを組み込む方法や、プロジェクト内のプロンプトを効率的に管理する方法などです。
### キャンバス式開発プラットフォームの構築
agentUniverseは、ローカルベースのキャンバス型開発プラットフォーム機能を提供しています。以下の手順に従って、迅速に起動してください。
**pipを使用**
```shell
pip install magent-ui ruamel.yaml
```
**一鍵で実行する**
sample_apps/workflow_agent_app/bootstrap/platformの下にある[product_application.py](examples/sample_apps/workflow_agent_app/bootstrap/platform/product_application.py)ファイルを実行して、一括起動します。
詳細については、[製品化プラットフォームの迅速な開始](./docs/guidebook/en/How-to/Guide to Visual Agentic Workflow Platform/Product_Platform_Quick_Start.md) と [製品化プラットフォームの進階ガイド](./docs/guidebook/en/How-to/Guide to Visual Agentic Workflow Platform/Product_Platform_Advancement_Guide.md) をご覧ください。本機能は 🔗[difizen](https://github.com/difizen/magent) プロジェクトチームと X agentUniverse プロジェクトチームが共同で提供しています。
****************************************
## なぜエージェントユニバースを使用するのか
### 設計の思考
![](docs/guidebook/_picture/agentuniverse_structure.png)
agentUniverseのコアは、単一のエージェントを構築するためのすべての重要なコンポーネント、マルチエージェント間の協力メカニズム、および専門家の経験を注入するメカニズムを提供し、開発者が専門的なノウハウを持つスマートアプリケーションを簡単に構築できるようにします。
### 多エージェント協調メカニズム
agentUniverseは、実際の産業で検証された有効なマルチエージェント協力モデルのコンポーネントをいくつか提供しており、その中で「PEER」は最も特徴的なモデルの一つです。
PEERパターン: このパターンは、Plan(計画)、Execute(実行)、Express(表現)、Review(レビュー)の4つの異なるエージェントの役割を利用して、複雑なタスクを多段階に分解し、順次実行します。また、評価フィードバックに基づいて自律的な反復を行い、推論および分析タスクのパフォーマンスを向上させます。
PEERモードはエキサイティングな結果を得ることができ、最新の研究成果や実験結果については以下の文献で読むことができます。
### いんよう
BibTeX formatted
```text
@misc{wang2024peerexpertizingdomainspecifictasks,
title={PEER: Expertizing Domain-Specific Tasks with a Multi-Agent Framework and Tuning Methods},
author={Yiying Wang and Xiaojing Li and Binzhu Wang and Yueyang Zhou and Han Ji and Hong Chen and Jinshi Zhang and Fei Yu and Zewei Zhao and Song Jin and Renji Gong and Wanqing Xu},
year={2024},
eprint={2407.06985},
archivePrefix={arXiv},
primaryClass={cs.AI},
url={https://arxiv.org/abs/2407.06985},
}
```
文献の紹介:この文献では、PEER多エージェントフレームワークのメカニズム原理について詳しく説明するとともに、実験部分では**完全性、関連性、簡潔性、事実性、論理性、構造性、包括性の7つの次元で評価(各次元の満点は5点)**を行っています。PEERモデルは各評価次元の平均スコアがBabyAGIを上回り、完全性、関連性、論理性、構造性、包括性の5つの次元で顕著な優位性を持っています。また、PEERモデルはGPT-3.5 turbo (16k)モードでBabyAGIに対して選抜勝率が83%に達し、GPT-4oモデルでは選抜勝率が81%に達しています。詳細については文献をご覧ください。
🔗https://arxiv.org/pdf/2407.06985
### コア特性
agentUniverseの主な特徴を以下のようにまとめました:
柔軟で拡張可能なエージェント構築能力: エージェント構築に必要なすべての重要コンポーネントを提供し、すべてのコンポーネントはユーザーが独自のエージェントを強化するためにカスタマイズをサポートします。
豊富で効果的なマルチエージェント協調モード: PEER(Plan/Execute/Express/Review)、DOE(Data-fining/Opinion-inject/Express)など、産業で検証された協調モードを提供し、ユーザーが新しいモードを自分で編成できるようにサポートし、複数のエージェントが有機的に協力できるようにします。
分野の経験を簡単に取り入れる: 分野に特化したプロンプト、知識の構築と管理能力を提供し、分野レベルのSOPを編成・注入することをサポートし、エージェントを分野の専門家レベルに合わせることができます。
💡 更なる特徴については、[agentUniverseの核心特性](docs/guidebook/en/Concepts/Core_Features.md)の部分を参照してください。
****************************************
## サンプルアプリ
🚩 [法律相談Agent_V2](docs/guidebook/en/Examples/Legal_Advice.md)
🚩 [Pythonコード生成と実行Agent](docs/guidebook/en/Examples/Python_Auto_Runner.md)
🚩 [多回多Agentによるディスカッショングループ](docs/guidebook/en/Examples/Discussion_Group.md)
🚩 [PEERマルチAgentモードに基づいた金融イベント分析](docs/guidebook/en/Examples/Financial_Event_Analysis.md)
🚩 [反射的ワークフロー翻訳エージェントの複製](docs/guidebook/en/Examples/Translation_Assistant.md)
****************************************
## 文書資料
### ユーザーガイドマニュアル
💡 詳細な情報については、[ユーザーガイド](./docs/guidebook/en/Contents.md)を参照してください。
### APIリファレンス
💡 [APIリファレンス](https://agentuniverse.readthedocs.io/en/latest/)を参照して、技術的な詳細をご確認ください。
****************************************
## サポート
### お問い合わせ
😊 Email:
* [jihan.hanji@antgroup.com](mailto:jihan.hanji@antgroup.com)
* [jerry.zzw@antgroup.com](mailto:jerry.zzw@antgroup.com)
* [jinshi.zjs@antgroup.com](mailto:jinshi.zjs@antgroup.com)
### twitter
ID: [@agentuniverse_](https://x.com/agentuniverse_)
+235
View File
@@ -0,0 +1,235 @@
# agentUniverse
****************************************
语言版本: [English](./README.md) | [中文](./README_zh.md) | [日本語](./README_jp.md)
![](https://img.shields.io/badge/framework-agentUniverse-pink)
![](https://img.shields.io/badge/python-3.10%2B-blue?logo=Python)
[![](https://img.shields.io/badge/%20license-Apache--2.0-yellow)](LICENSE)
[![Static Badge](https://img.shields.io/badge/pypi-v0.0.19-blue?logo=pypi)](https://pypi.org/project/agentUniverse/)
![](docs/guidebook/_picture/logo_bar.jpg)
****************************************
## agentUniverse是什么?
**agentUniverse 是一个基于大型语言模型的多智能体框架。** agentUniverse为您提供灵活易拓展的单智能体构建能力;agentUniverse核心拥有丰富的多智能体协同模式组件(可视为一个协同模式工厂Pattern Factory),它能让智能体们各司其职在解决不同领域问题时发挥最大的能力;同时agentUniverse专注于领域经验的融合,帮助您轻松将领域经验融入到智能体的工作中。🎉🎉🎉
**🌈🌈🌈agentUniverse源自于蚂蚁集团(https://github.com/antgroup) 的真实金融业务实践,致力于帮助开发者、企业轻松构建出领域专家级别的强大智能体,协同完成工作。**
![](docs/guidebook/_picture/agent_universe_framework_resize.jpg)
我们期待您通过社区对不同领域的Pattern进行实践与交流共享,框架也预置有若干已在真实产业中验证有效的多智能体协作模式组件,并在未来持续丰富。目前即将开放的模式组件包括:
* PEER 模式组件: 该pattern通过计划(Plan)、执行(Execute)、表达(Express)、评价(Review)四个不同职责的智能体,实现对复杂问题的多步拆解、分步执行,并基于评价反馈进行自主迭代,最终提升推理分析类任务表现。典型适用场景:事件解读、行业分析
* DOE 模式组件: 该pattern通过数据精制(Data-fining)、观点注入(Opinion-inject)、表达(Express)三个智能体,实现对数据密集、高计算精度、融合专家观点的生成任务的效果提升。典型适用场景:财报生成
更多模式组件持续推出中...
The LLM model integration can be accomplished with simple configuration, currently agentUniverse supported models include:
|-|供应商| 模型 |
|:-----:|:--------:|:------------------------------------------------------------------------------------------------------------:|
|<img src="https://github.com/user-attachments/assets/b7b0f2ce-3250-4008-b6d7-4712a983deb9" height="25">|Qwen| qwen3 Series(qwen3-235b-a22b、qwen3-32b、qwen3-30b-a3b, etc.) 、qwen2.5-72b-instruct、qwq-32b-preview、qwen-max、… |
|<img src="https://github.com/user-attachments/assets/5a997feb-bef4-4e53-ac3e-d38221e5399c" height="25">|Deepseek| deepseek-r1、deepseek-v3、deepseek-r1-distill-qwen-32b、… |
|<img src="https://github.com/user-attachments/assets/0b50e555-65e8-49b2-b725-f3f71ee7daed" height="25">|OpenAI| GPT-4o、GPT-4o mini、OpenAI o1、OpenAI o3-mini、… |
|<img src="https://github.com/user-attachments/assets/60fe0a70-0b47-4ac7-9bc9-8e860732ace9" height="25">|Claude| claude 3.7 sonnet 、Claude 3.5 Sonnet、Claude 3 Opus、… |
|<img src="https://github.com/user-attachments/assets/334c7f09-7eae-4a65-a70f-2e6531964224" height="25">|Gemini| Gemini 2.5 Pro、Gemini 2.0 Flash、Gemini 2.0 Flash Thinking、Gemini 1.5 Pro、… |
|<img src="https://github.com/user-attachments/assets/8e41c73f-3103-4305-ad1f-56116ea55523" height="25">|Llama| llama3.3-70b-instruct、llama3.2-3b-instruct、llama3.2-1b-instruct、… |
|<img src="https://github.com/user-attachments/assets/19d264c6-e499-4913-9d6d-314d392f2246" height="25">|KIMI| moonshot-v1-128k、moonshot-v1-32k、moonshot-v1-8k、… |
|<img src="https://github.com/user-attachments/assets/79572d9a-29d5-4c0e-a336-ce3f8018fb05" height="25">|WenXin| ERNIE 4.5 Turbo、ERNIE 4.5、ERNIE 4.0 Turbo、ERNIE 4.0、ERNIE 3.5、… |
|<img src="https://github.com/user-attachments/assets/abb5311e-4d70-4e9c-8fca-e5129ae912fc" height="25">|chatglm| chatglm3-6b、chatglm-6b-v2、… |
|<img src="https://github.com/user-attachments/assets/fe265f24-4ea6-4ff2-9b50-58ab6706a5f5" height="25">|BaiChuan| baichuan2-turbo、baichuan2-13b-chat-v1、… |
|<img src="https://github.com/user-attachments/assets/41ffe268-392f-4ab9-b42d-e30dbd70d66b" height="25">|Doubao| Doubao-pro-128k、Doubao-pro-32k、Doubao-lite-128k、… |
****************************************
## 目录
* [快速开始](#快速开始)
| &nbsp; [快速安装](#快速安装) &nbsp; |
&nbsp; [运行案例](#运行第一个教程案例) &nbsp; |
* [如何搭建一个智能体应用](#如何搭建一个智能体应用)
| &nbsp; [标准工程脚手架搭建](#标准工程脚手架) &nbsp; |
&nbsp; [画布式研发平台搭建](#画布式研发平台搭建) &nbsp; |
* [为什么使用agentUniverse](#为什么使用agentUniverse)
| &nbsp; [设计思路](#设计思路) &nbsp; |
&nbsp; [协同机制](#多智能体协同机制) &nbsp; |
&nbsp; [研究文献](#文献) &nbsp; |
&nbsp; [核心特性](#核心特性) &nbsp; |
* [应用实践](#应用实践)
| &nbsp; [应用实践案例](#应用实践案例) &nbsp; |
&nbsp; [典型产品](#使用aU构建的典型产品) &nbsp; |
* [用户指南手册](#用户指南手册)
* [更多](#更多)
| &nbsp; Roadmap &nbsp; |
&nbsp; [API说明](#API参考) &nbsp; |
&nbsp; [项目支持](#支持) &nbsp; |
&nbsp;&nbsp; [鸣谢](#鸣谢) &nbsp;&nbsp; |
****************************************
## 快速开始
### 快速安装
使用pip:
```shell
pip install agentUniverse
```
### 运行第一个教程案例
运行您的第一个案例,您可以通过教程快速体验agentUniverse构建出的智能体(组)运行效果。
详细步骤请阅读文档: [运行第一个教程案例](./docs/guidebook/zh/开始使用/2.运行第一个教程案例.md) 。
****************************************
## 如何搭建一个智能体应用
### 标准工程脚手架
⌨️ 标准工程脚手架:[agentUniverse Standard Project](examples/sample_standard_app)
#### 快速构建单体智能体
您可以通过 [快速构建单体智能体](./docs/guidebook/zh/开始使用/3.快速构建单体智能体.md) 章节的阅读与体验了解如何快速构建单个智能体,并掌握如何通过工具、知识库、RAG技术等能力增强您的智能体能力,同时掌握智能体配置、测试、调优、服务化、效果评估等一系列基本的智能体应用研发流程。
#### 构建典型的多智能体应用
您可以通过 [构建典型的多智能体应用](./docs/guidebook/zh/开始使用/4.构建典型的多智能体应用.md) 章节进一步了解在复杂的任务场景,如何将智能体能力拆分成多个智能体,并让其通过协同进一步提升您的任务表现。
#### 沉淀与使用智能体模版
您可以通过 [沉淀与使用智能体模版](./docs/guidebook/zh/开始使用/5.沉淀与使用智能体模版.md) 章节了解如何将有效的智能体模式沉淀成模版,这将大大提升后续智能体的构建效率并便于传播。
#### 使用与发布MCP服务
您可以通过 [如何使用MCP服务](./docs/guidebook/zh/How-to/使用与发布MCP服务/如何使用MCP服务.md)、[如何发布MCP服务](./docs/guidebook/zh/How-to/使用与发布MCP服务/如何发布MCP服务.md) 章节掌握如何快速在智能体框架中使用或发布MCP服务。
#### 智能体应用观测
agentUniverse拥有标准的智能体应用观测标准,并基于OpenTelemetry协议对于智能体、模型、工具等重要组件进行全方位采集与观测,方便用户追踪智能体全生命周期,您可以在 [智能体应用可观测](./docs/guidebook/zh/In-Depth_Guides/技术组件/可观测/基于OTEL的可观测能力.md) 章节掌握如何使用观测能力。
#### 常用使用技巧
您可以通过 [开始章节](./docs/guidebook/zh/开始使用) 下的其他文档了解智能体应用构建过程中的其他进阶技巧,例如如何在智能体过程中加入记忆模块、如何有效的管理项目中的prompt等。
### 画布式研发平台搭建
agentUniverse提供基于本地的画布式研发平台能力,请按照如下步骤快速启动。
**通过pip安装**
```shell
pip install magent-ui ruamel.yaml
```
**一键运行**
运行sample_apps/workflow_agent_app/bootstrap/platform下的[product_application.py](examples/sample_apps/workflow_agent_app/bootstrap/platform/product_application.py)文件,一键启动。
更多详情参考 [产品化平台快速开始](./docs/guidebook/zh/How-to/画布式研发平台使用/画布式研发平台快速开始.md)
与 [产品化平台进阶指南](./docs/guidebook/zh/How-to/画布式研发平台使用/画布式研发平台进阶指南.md) 。本功能由 🔗[difizen](https://github.com/difizen/magent) 项目组 X agentUniverse 项目组联合推出。
****************************************
## 为什么使用agentUniverse
### 设计思路
![](docs/guidebook/_picture/agentuniverse_structure.png)
agentUniverse核心提供了搭建单一智能体的全部关键组件、多智能体之间的协作机制、以及专家经验的注入机制,可以帮助开发者轻松构建具备专业KnowHow的智能应用。
### 多智能体协同机制
agentUniverse提供了若干已在真实产业中验证有效的多智能体协作模式组件,其中,“PEER”是最具特色的模式之一。
PEER模式通过计划(Planning)、执行(Executing)、表达(Expressing)、评价(Reviewing)四个不同职责的智能体,实现对复杂问题的多步拆解、分步执行,并基于评价反馈进行自主迭代,最终提升推理分析类任务表现。这一模式显著适用于需要多步拆解、深度分析的场景,比如对于事件的解读、宏中观经济分析、商业方案的可行性分析等。
PEER模式取得了令人兴奋的效果,最新的研究成果与实验结果我们可以在下列文献中阅读。
### 文献
BibTeX formatted
```text
@misc{wang2024peerexpertizingdomainspecifictasks,
title={PEER: Expertizing Domain-Specific Tasks with a Multi-Agent Framework and Tuning Methods},
author={Yiying Wang and Xiaojing Li and Binzhu Wang and Yueyang Zhou and Han Ji and Hong Chen and Jinshi Zhang and Fei Yu and Zewei Zhao and Song Jin and Renji Gong and Wanqing Xu},
year={2024},
eprint={2407.06985},
archivePrefix={arXiv},
primaryClass={cs.AI},
url={https://arxiv.org/abs/2407.06985},
}
```
文献简介:该文献详细介绍了介绍了PEER多智能体框架的机制原理,同时在实验部分分别从**完整性、相关性、紧凑性、事实性、逻辑性、结构性和全面性七个维度进行打分(各纬度满分为5分)**,PEER模式在每个测评维度的平均分数均高于BabyAGI,且在**完整性、相关性、逻辑性、结构性和全面性五个纬度有显著优势**;同时PEER模式在 GPT-3.5 turbo (16k) 模型下相较于 BabyAGI 的择优胜率达到 83%,在 GPT-4o 模型下择优胜率达到 81%,更多详情请阅读文献。
🔗https://arxiv.org/pdf/2407.06985
### 核心特性
通过上述的介绍我们将其归纳总结,agentUniverse包含如下主要特点:
灵活易拓的智能体构建能力: 提供智能体构建所必须的全部关键组件,所有组件均可支持定制供用户增强专属智能体;
丰富有效的多智能体协同模式: 提供PEER(Plan/Execute/Express/Review)、DOE(Data-fining/Opinion-inject/Express)等产业中验证有效的协同模式,支持用户自定义编排新模式,让多个智能体有机合作;
轻松融入领域经验: 提供领域prompt、知识构建与管理的能力,支持领域级SOP编排与注入,将智能体对齐至领域专家级别;
💡 更多特点见[agentUniverse核心特性](./docs/guidebook/zh/设计理念/核心特性.md)部分。
****************************************
## 应用实践
### 应用实践案例
🚩 [法律咨询Agent_v2](docs/guidebook/zh/实践应用/法律咨询案例.md)
🚩 [Python代码生成与执行Agent](docs/guidebook/zh/实践应用/Python自动执行案例.md)
🚩 [基于多轮多Agent的讨论小组](docs/guidebook/zh/实践应用/讨论组.md)
🚩 [基于PEER协同模式的金融事件分析](docs/guidebook/zh/实践应用/金融事件分析案例.md)
🚩 [吴恩达反思工作流翻译智能体复刻](docs/guidebook/zh/实践应用/翻译案例.md)
### 使用aU构建的典型产品
🔗[支小助-金融从业专家AI助手](https://zhu.alipay.com/?from=au)
**投研支小助:助推大模型落地严谨产业,提升投研专家效率**
投研支小助是大模型落地严谨产业的高效解决方案,基于专注严谨应用的凤凰大模型和善于专业定制的agentUniverse智能体框架,主要面向投研、ESG、财经、财报等投研相关细分领域的一系列专业AI业务助手,已在蚂蚁大规模场景充分验证,提升专家效率。
https://private-user-images.githubusercontent.com/39180831/355437700-192f712d-1b03-46a6-8422-1ca10aa94331.mp4?jwt=eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJpc3MiOiJnaXRodWIuY29tIiwiYXVkIjoicmF3LmdpdGh1YnVzZXJjb250ZW50LmNvbSIsImtleSI6ImtleTUiLCJleHAiOjE3MjI5NDk4NTAsIm5iZiI6MTcyMjk0OTU1MCwicGF0aCI6Ii8zOTE4MDgzMS8zNTU0Mzc3MDAtMTkyZjcxMmQtMWIwMy00NmE2LTg0MjItMWNhMTBhYTk0MzMxLm1wND9YLUFtei1BbGdvcml0aG09QVdTNC1ITUFDLVNIQTI1NiZYLUFtei1DcmVkZW50aWFsPUFLSUFWQ09EWUxTQTUzUFFLNFpBJTJGMjAyNDA4MDYlMkZ1cy1lYXN0LTElMkZzMyUyRmF3czRfcmVxdWVzdCZYLUFtei1EYXRlPTIwMjQwODA2VDEzMDU1MFomWC1BbXotRXhwaXJlcz0zMDAmWC1BbXotU2lnbmF0dXJlPTU4NWMzNzVjOGZjZDNjMDMzMTE4YjQzOTk0ZWQwZGZkNWNmNWQxNWMzYWIzMTk4MzY1MjA5NWRhMjU2NGNiNzUmWC1BbXotU2lnbmVkSGVhZGVycz1ob3N0JmFjdG9yX2lkPTAma2V5X2lkPTAmcmVwb19pZD0wIn0.q1vdSg_Ghxr-DHLXfmQ_fVVRVSFn7H8VMHMi-_2QrjA
****************************************
## 用户指南手册
💡 更多详细信息,请阅读[用户指南手册](docs/guidebook/zh/目录.md) 。
****************************************
## 更多
### API参考
💡 请阅读[readthedocs](https://agentuniverse.readthedocs.io/en/latest/) 。
### 支持
#### 通过github issue提交疑问
😊 我们建议您使用[github issue](https://github.com/agentuniverse-ai/agentUniverse/issues) 提交您的疑问, 我们通常会在2日内回复。
#### 通过Discord联系我们
😊 加入我们的 [Discord频道](https://discord.gg/DHFcdkWAhn) 与我们进行交流。
#### 通过钉钉群联系我们
😊 加入我们的钉钉答疑群与我们联系。
![](./docs/guidebook/_picture/dingtalk_util20250429.png)
#### 通过管理员Email联系我们
😊 Email:
* [jihan.hanji@antgroup.com](mailto:jihan.hanji@antgroup.com)
* [jerry.zzw@antgroup.com](mailto:jerry.zzw@antgroup.com)
* [jinshi.zjs@antgroup.com](mailto:jinshi.zjs@antgroup.com)
#### 微信公众号
😊 公众号ID:**agentUniverse智多星**
![](./docs/guidebook/_picture/wechat_official.png)
更多相关的文章与资讯你可以在微信公众号中获取。
#### twitter
ID: [@agentuniverse_](https://x.com/agentuniverse_)
### 鸣谢
本项目部分基于langchain、pydantic、gunicorn、flask、SQLAlchemy、chromadb等(详细依赖列表可见pyproject.toml)优秀开源项目实现,在此特别感谢相关项目与关联方。 🙏🙏🙏
+7
View File
@@ -0,0 +1,7 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/4/2 11:11
# @Author : jerry.zzw
# @Email : jerry.zzw@antgroup.com
# @FileName: __init__.py
+7
View File
@@ -0,0 +1,7 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/4/2 15:19
# @Author : jerry.zzw
# @Email : jerry.zzw@antgroup.com
# @FileName: __init__.py
+7
View File
@@ -0,0 +1,7 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/4/2 17:05
# @Author : wangchongshi
# @Email : wangchongshi.wcs@antgroup.com
# @FileName: __init__.py
@@ -0,0 +1,7 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/4/2 17:06
# @Author : wangchongshi
# @Email : wangchongshi.wcs@antgroup.com
# @FileName: __init__.py
@@ -0,0 +1,7 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/7/23 13:59
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: __init__.py
@@ -0,0 +1,543 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/12/04 00:00
# @Author : AI Assistant
# @Email : ai@example.com
# @FileName: academic_paper_fragmenter.py
import re
import logging
from typing import List, Optional, Dict, Set, Tuple
from dataclasses import dataclass
from datetime import datetime
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import DocProcessor
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
logger = logging.getLogger(__name__)
@dataclass
class PaperSection:
"""Represents a section in an academic paper.
Attributes:
name: Section name (e.g., 'Abstract', 'Introduction').
text: Content of the section.
start_pos: Starting position in original text.
end_pos: Ending position in original text.
"""
name: str
text: str
start_pos: int
end_pos: int
@dataclass
class Argument:
"""Represents an argument or claim in the paper.
Attributes:
text: The argument text.
argument_type: Type of argument (thesis, evidence, conclusion).
section: Section containing this argument.
citations: List of citations supporting this argument.
position: Position in the section.
"""
text: str
argument_type: str
section: str
citations: List[str]
position: int
class AcademicPaperFragmenter(DocProcessor):
"""Fragment academic papers by arguments and evidence.
This processor analyzes academic papers and fragments them by:
1. Detecting paper structure (Abstract, Introduction, Methods, Results, Discussion)
2. Identifying thesis statements vs supporting evidence
3. Extracting citations and linking them to evidence
4. Creating documents with rich metadata about argument types and relationships
Attributes:
detect_sections: Whether to detect and parse paper sections.
extract_citations: Whether to extract citation information.
link_evidence: Whether to link evidence to claims.
section_patterns: Dictionary of regex patterns for section detection.
min_argument_length: Minimum length for a valid argument (characters).
skip_on_error: Whether to skip documents that fail processing.
"""
detect_sections: bool = True
extract_citations: bool = True
link_evidence: bool = True
section_patterns: Optional[Dict[str, str]] = None
min_argument_length: int = 20 # Lowered from 50 to capture shorter arguments
skip_on_error: bool = True
def __init__(self, **data):
super().__init__(**data)
if self.section_patterns is None:
self.section_patterns = {
'abstract': r'^(Abstract|ABSTRACT|摘\s*要)',
'introduction': r'^(Introduction|INTRODUCTION|1\.?\s*Introduction|引\s*言|绪\s*论|1\.?\s*引言)',
'related_work': r'^(Related\s+Work|RELATED\s+WORK|Literature\s+Review|2\.?\s*Related\s+Work|相关工作)',
'methods': r'^(Methods?|METHODS?|Methodology|METHODOLOGY|3\.?\s*Method|方\s*法|实验方法)',
'results': r'^(Results?|RESULTS?|Experiments?|EXPERIMENTS?|4\.?\s*Results?|实\s*验|结\s*果)',
'discussion': r'^(Discussion|DISCUSSION|Analysis|ANALYSIS|5\.?\s*Discussion|讨\s*论|分\s*析)',
'conclusion': r'^(Conclusions?|CONCLUSIONS?|6\.?\s*Conclusion|结\s*论)',
'references': r'^(References|REFERENCES|Bibliography|参考文献)',
}
def _process_docs(self, origin_docs: List[Document], query: Query = None) -> List[Document]:
"""Fragment academic papers into argument-based documents.
Args:
origin_docs: List of academic paper documents to fragment.
query: Optional query object (not used in this processor).
Returns:
List of argument documents with metadata.
"""
if not origin_docs:
return []
logger.info(f"Starting academic paper fragmentation of {len(origin_docs)} documents")
all_argument_docs = []
for doc in origin_docs:
try:
argument_docs = self._fragment_document(doc)
all_argument_docs.extend(argument_docs)
logger.info(f"Fragmented paper {doc.id} into {len(argument_docs)} arguments")
except Exception as e:
logger.error(f"Failed to fragment document {doc.id}: {e}")
if not self.skip_on_error:
raise
# Pass through original document if skip_on_error is True
all_argument_docs.append(doc)
logger.info(f"Total argument fragments created: {len(all_argument_docs)}")
return all_argument_docs
def _fragment_document(self, doc: Document) -> List[Document]:
"""Fragment a single academic paper into arguments.
Args:
doc: Academic paper document to fragment.
Returns:
List of argument documents.
"""
text = doc.text
# Step 1: Detect sections if enabled
sections = []
if self.detect_sections:
sections = self._identify_sections(text)
logger.debug(f"Detected {len(sections)} sections")
# If no sections detected, treat as single section
if not sections:
sections = [PaperSection('full_text', text, 0, len(text))]
# Step 2: Extract arguments from each section
all_arguments = []
for section in sections:
arguments = self._extract_arguments(section)
all_arguments.extend(arguments)
# Step 3: Extract citations if enabled
citations = []
if self.extract_citations:
citations = self._parse_citations(text)
logger.debug(f"Extracted {len(citations)} citations")
# Step 4: Link evidence to claims if enabled
if self.link_evidence and citations:
self._link_evidence_to_claims(all_arguments, citations)
# Step 5: Create documents for each argument
argument_docs = self._create_argument_documents(doc, all_arguments)
return argument_docs
def _identify_sections(self, text: str) -> List[PaperSection]:
"""Identify sections in the academic paper.
Args:
text: Full paper text.
Returns:
List of PaperSection objects.
"""
sections = []
lines = text.split('\n')
current_pos = 0
section_boundaries = [] # List of (line_idx, section_name, start_pos)
# Find section headers
for line_idx, line in enumerate(lines):
line_stripped = line.strip()
if not line_stripped:
current_pos += len(line) + 1
continue
# Check against section patterns
matched = False
for section_name, pattern in self.section_patterns.items():
if re.match(pattern, line_stripped, re.IGNORECASE):
section_boundaries.append((line_idx, section_name, current_pos))
logger.debug(f"Found section '{section_name}' at line {line_idx}")
matched = True
break
# Additional detection for numbered sections (e.g., "1. ", "1.1 ", "1. Introduction")
if not matched:
# Match patterns like "1. Introduction", "1.1 Background", "2. Methods"
numbered_match = re.match(r'^(\d+(\.\d+)*\.?)\s+([A-Za-z\u4e00-\u9fa5][A-Za-z\u4e00-\u9fa5\s]+)$', line_stripped)
if numbered_match:
section_number = numbered_match.group(1)
section_title = numbered_match.group(3).strip().lower()
# Try to map to known sections
section_name = self._map_to_known_section(section_title)
if section_name:
section_boundaries.append((line_idx, section_name, current_pos))
logger.debug(f"Found numbered section '{section_name}' ({section_number}) at line {line_idx}")
matched = True
else:
# If not a known section, use the section title as section name
# This allows detection of custom sections like "1.1 Background"
safe_title = re.sub(r'[^\w\s]', '', section_title).strip().replace(' ', '_')
if safe_title:
section_boundaries.append((line_idx, safe_title, current_pos))
logger.debug(f"Found numbered custom section '{safe_title}' at line {line_idx}")
matched = True
# Detection for simple capitalized headers (more aggressive)
if not matched and len(line_stripped) > 2 and len(line_stripped) < 50:
# Check if line looks like a section header:
# - Starts with capital letter OR Chinese character
# - Short enough to be a title
# - No punctuation at the end (except for numbered sections)
# - Not too many words (< 8 words)
words = line_stripped.split()
is_chinese = bool(re.match(r'^[\u4e00-\u9fa5]', line_stripped)) # Starts with Chinese char
if (len(words) <= 8 and
(line_stripped[0].isupper() or is_chinese) and
not line_stripped.endswith('.') and
not line_stripped.endswith(',') and
not line_stripped.endswith(';')):
# Try to map to known sections
section_title = line_stripped.lower()
section_name = self._map_to_known_section(section_title)
if section_name:
section_boundaries.append((line_idx, section_name, current_pos))
logger.debug(f"Found simple header section '{section_name}' at line {line_idx}")
matched = True
# Detection for ALL CAPS headers
if not matched and len(line_stripped) > 3 and len(line_stripped) < 50:
if line_stripped.isupper():
section_title = line_stripped.lower()
section_name = self._map_to_known_section(section_title)
if section_name:
section_boundaries.append((line_idx, section_name, current_pos))
logger.debug(f"Found CAPS section '{section_name}' at line {line_idx}")
matched = True
current_pos += len(line) + 1
# Create sections from boundaries
for i, (line_idx, section_name, start_pos) in enumerate(section_boundaries):
# Determine end position
if i + 1 < len(section_boundaries):
end_pos = section_boundaries[i + 1][2]
else:
end_pos = len(text)
# Extract section text
section_text = text[start_pos:end_pos].strip()
# Remove section header from text
first_newline = section_text.find('\n')
if first_newline != -1:
section_text = section_text[first_newline:].strip()
if section_text: # Only add non-empty sections
sections.append(PaperSection(
name=section_name,
text=section_text,
start_pos=start_pos,
end_pos=end_pos
))
return sections
def _map_to_known_section(self, title: str) -> Optional[str]:
"""Map section title to known section types.
Args:
title: Section title (lowercase).
Returns:
Section name or None.
"""
mapping = {
'abstract': ['abstract', '摘要'],
'introduction': ['introduction', 'intro', 'background', '引言', '绪论'],
'related_work': ['related work', 'literature review', 'prior work', '相关工作'],
'methods': ['method', 'methods', 'methodology', 'approach', '方法', '实验方法'],
'results': ['result', 'results', 'experiment', 'experiments', 'findings', '实验', '结果'],
'discussion': ['discussion', 'analysis', '讨论', '分析'],
'conclusion': ['conclusion', 'conclusions', 'summary', '结论'],
'references': ['reference', 'references', 'bibliography', '参考文献'],
}
title_lower = title.lower()
for section_name, keywords in mapping.items():
for keyword in keywords:
if keyword in title_lower:
return section_name
return None
def _extract_arguments(self, section: PaperSection) -> List[Argument]:
"""Extract arguments from a paper section.
Args:
section: PaperSection to analyze.
Returns:
List of Argument objects.
"""
arguments = []
# Split section into paragraphs - handle both \n\n and single \n
text = section.text.strip()
# First try splitting by double newlines (standard paragraphs)
paragraphs = [p.strip() for p in text.split('\n\n') if p.strip()]
# If we get very few paragraphs, try splitting by single newlines
# This handles cases where sections are separated by single line breaks
if len(paragraphs) < 2:
paragraphs = [p.strip() for p in text.split('\n') if p.strip()]
for idx, paragraph in enumerate(paragraphs):
if len(paragraph) < self.min_argument_length:
continue
# Determine argument type based on section and content
argument_type = self._classify_argument(paragraph, section.name)
# Extract citations in this paragraph
paragraph_citations = self._extract_paragraph_citations(paragraph)
argument = Argument(
text=paragraph,
argument_type=argument_type,
section=section.name,
citations=paragraph_citations,
position=idx
)
arguments.append(argument)
return arguments
def _classify_argument(self, text: str, section_name: str) -> str:
"""Classify the type of argument.
Args:
text: Argument text.
section_name: Name of the section containing the argument.
Returns:
Argument type: 'thesis', 'evidence', 'methodology', or 'conclusion'.
"""
# Section-based classification
if section_name in ['abstract', 'introduction']:
# Look for thesis indicators
thesis_indicators = [
r'\bwe\s+(propose|present|introduce|demonstrate)',
r'\bthis\s+paper\s+(presents|proposes|introduces)',
r'\bour\s+(contribution|approach|method)',
r'\bin\s+this\s+(work|paper|study)',
]
for pattern in thesis_indicators:
if re.search(pattern, text, re.IGNORECASE):
return 'thesis'
if section_name in ['methods', 'methodology']:
return 'methodology'
if section_name in ['results', 'experiments']:
# Evidence with experimental support
return 'evidence'
if section_name in ['conclusion', 'conclusions']:
return 'conclusion'
# Content-based classification
evidence_indicators = [
r'\b(figure|table|shown|demonstrates?|shows?)\s+\d+',
r'\b(experiment|study|test|evaluation)\s+(shows?|demonstrates?)',
r'\b(results?|findings?)\s+(show|demonstrate|indicate)',
]
for pattern in evidence_indicators:
if re.search(pattern, text, re.IGNORECASE):
return 'evidence'
# Default to general claim
return 'claim'
def _parse_citations(self, text: str) -> List[str]:
"""Parse citations from the text.
Args:
text: Paper text.
Returns:
List of citation identifiers.
"""
citations = []
# Common citation patterns
patterns = [
r'\[(\d+)\]', # [1], [2]
r'\[(\d+,\s*\d+(?:,\s*\d+)*)\]', # [1, 2, 3]
r'\[(\d+-\d+)\]', # [1-5]
r'\(([A-Z][a-z]+\s+et\s+al\.,?\s+\d{4})\)', # (Smith et al., 2020)
r'\(([A-Z][a-z]+\s+and\s+[A-Z][a-z]+,?\s+\d{4})\)', # (Smith and Jones, 2020)
r'\(([A-Z][a-z]+,?\s+\d{4})\)', # (Smith, 2020)
]
for pattern in patterns:
matches = re.finditer(pattern, text)
for match in matches:
citation = match.group(1)
if citation not in citations:
citations.append(citation)
return citations
def _extract_paragraph_citations(self, paragraph: str) -> List[str]:
"""Extract citations from a specific paragraph.
Args:
paragraph: Paragraph text.
Returns:
List of citation identifiers in the paragraph.
"""
return self._parse_citations(paragraph)
def _link_evidence_to_claims(self, arguments: List[Argument], all_citations: List[str]) -> None:
"""Link evidence to claims based on shared citations.
Args:
arguments: List of arguments to analyze.
all_citations: All citations in the paper.
Note:
Modifies arguments in place.
"""
# Build citation index
citation_to_args: Dict[str, List[int]] = {}
for idx, arg in enumerate(arguments):
for citation in arg.citations:
if citation not in citation_to_args:
citation_to_args[citation] = []
citation_to_args[citation].append(idx)
# Link related arguments through shared citations
# This creates implicit relationships for metadata
logger.debug(f"Linked arguments through {len(citation_to_args)} shared citations")
def _create_argument_documents(self, original_doc: Document,
arguments: List[Argument]) -> List[Document]:
"""Create Document objects for each argument.
Args:
original_doc: Original paper document.
arguments: List of argument objects.
Returns:
List of argument documents.
"""
argument_docs = []
for arg in arguments:
# Build metadata
metadata = {
'processor_name': self.name,
'processor_version': '1.0',
'processing_timestamp': datetime.now().isoformat(),
'source_document_id': original_doc.id,
'section': arg.section,
'argument_type': arg.argument_type,
'position': arg.position,
}
# Add original metadata
if original_doc.metadata:
metadata['original_metadata'] = original_doc.metadata
# Add citations
if arg.citations:
metadata['citations'] = arg.citations
metadata['citation_count'] = len(arg.citations)
# Create keywords from argument type and section
keywords = original_doc.keywords.copy() if original_doc.keywords else set()
keywords.add(arg.section)
keywords.add(arg.argument_type)
# Create document
doc = Document(
text=arg.text,
metadata=metadata,
keywords=keywords
)
argument_docs.append(doc)
return argument_docs
def _initialize_by_component_configer(self,
doc_processor_configer: ComponentConfiger) -> 'AcademicPaperFragmenter':
"""Initialize fragmenter parameters from configuration.
Args:
doc_processor_configer: Configuration object containing fragmenter parameters.
Returns:
Initialized document processor instance.
"""
super()._initialize_by_component_configer(doc_processor_configer)
if hasattr(doc_processor_configer, "detect_sections"):
self.detect_sections = doc_processor_configer.detect_sections
if hasattr(doc_processor_configer, "extract_citations"):
self.extract_citations = doc_processor_configer.extract_citations
if hasattr(doc_processor_configer, "link_evidence"):
self.link_evidence = doc_processor_configer.link_evidence
if hasattr(doc_processor_configer, "section_patterns"):
self.section_patterns = doc_processor_configer.section_patterns
if hasattr(doc_processor_configer, "min_argument_length"):
self.min_argument_length = doc_processor_configer.min_argument_length
if hasattr(doc_processor_configer, "skip_on_error"):
self.skip_on_error = doc_processor_configer.skip_on_error
return self
@@ -0,0 +1,20 @@
name: 'academic_paper_fragmenter'
description: 'Fragment academic papers by arguments and evidence with section detection and citation extraction'
detect_sections: true
extract_citations: true
link_evidence: true
min_argument_length: 50
skip_on_error: true
section_patterns:
abstract: '^(Abstract|ABSTRACT|摘\s*要)'
introduction: '^(Introduction|INTRODUCTION|引\s*言|绪\s*论)'
related_work: '^(Related\s+Work|RELATED\s+WORK|Literature\s+Review|相关工作)'
methods: '^(Methods?|METHODS?|Methodology|METHODOLOGY|方\s*法)'
results: '^(Results?|RESULTS?|Experiments?|EXPERIMENTS?|实\s*验|结\s*果)'
discussion: '^(Discussion|DISCUSSION|Analysis|ANALYSIS|讨\s*论|分\s*析)'
conclusion: '^(Conclusions?|CONCLUSIONS?|结\s*论)'
references: '^(References|REFERENCES|Bibliography|参考文献)'
metadata:
type: 'DOC_PROCESSOR'
module: 'agentuniverse.agent.action.knowledge.doc_processor.academic_paper_fragmenter'
class: 'AcademicPaperFragmenter'
@@ -0,0 +1,79 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/8/5 14:37
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: character_text_splitter.py
from typing import List, Optional
from langchain.text_splitter import CharacterTextSplitter as Splitter
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import \
DocProcessor
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.config.component_configer.component_configer import \
ComponentConfiger
class CharacterTextSplitter(DocProcessor):
"""Character-based text splitter for document processing.
This class splits documents into smaller chunks based on character separators,
with configurable chunk size and overlap parameters.
Attributes:
chunk_size: The size of each text chunk.
chunk_overlap: The number of characters to overlap between chunks.
separator: The character sequence used to split text.
splitter: The underlying LangChain text splitter instance.
"""
chunk_size: int = 200
chunk_overlap: int = 20
separator: str = "/n/n"
__splitter: Optional[Splitter] = None
@property
def splitter(self) -> Splitter:
if not self.__splitter:
self.__splitter = Splitter(separator=self.separator,
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap)
return self.__splitter
def _process_docs(self, origin_docs: List[Document], query: Query = None) -> \
List[Document]:
"""Process documents by splitting them into smaller chunks.
Args:
origin_docs: List of original documents to be processed.
query: Optional query object that may influence the processing.
Returns:
List[Document]: List of processed document chunks.
"""
lc_doc_list = self.splitter.split_documents(Document.as_langchain_list(
origin_docs
))
return Document.from_langchain_list(lc_doc_list)
def _initialize_by_component_configer(self,
doc_processor_configer: ComponentConfiger) -> 'DocProcessor':
"""Initialize the splitter using configuration from a ComponentConfiger.
Args:
doc_processor_configer: Configuration object containing splitter parameters.
Returns:
DocProcessor: The initialized document processor instance.
"""
super()._initialize_by_component_configer(doc_processor_configer)
if hasattr(doc_processor_configer, "chunk_size"):
self.chunk_size = doc_processor_configer.chunk_size
if hasattr(doc_processor_configer, "chunk_overlap"):
self.chunk_overlap = doc_processor_configer.chunk_overlap
if hasattr(doc_processor_configer, "separator"):
self.separator = doc_processor_configer.separator
return self
@@ -0,0 +1,9 @@
name: 'character_text_splitter'
description: 'langchain character text splitter'
chunk_size: 200
chunk_overlap: 20
separators: "/n/n"
metadata:
type: 'DOC_PROCESSOR'
module: 'agentuniverse.agent.action.knowledge.doc_processor.character_text_splitter'
class: 'CharacterTextSplitter'
@@ -0,0 +1,311 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2025/03/04 14:09
# @Author : hiro
# @Email : hiromesh@qq.com
# @FileName: code_ast_processor.py
import json
from typing import List, Dict, Any, Optional, cast
from agentuniverse.agent.action.knowledge.doc_processor.types.ast_types import AstNode, AstNodePoint, CodeBoundary
from agentuniverse.agent.action.knowledge.doc_processor.types.code_types import CodeFeatures, CodeRepresentation, ChunkRepresentation
from agentuniverse.agent.action.knowledge.doc_processor.types.metrics_types import CodeMetrics
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import DocProcessor
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
class CodeAstProcessor(DocProcessor):
max_depth: int = 8
language_dir: str = None
chunk_size: int = 1000
chunk_overlap: int = 200
max_node_len: int = 100
_parser: Optional[Any] = None
_languages: Dict[str, Any] = {}
def _process_docs(self, origin_docs: List[Document], query: Query = None) -> List[Document]:
result_docs = []
for doc in origin_docs:
code = doc.text
language = doc.metadata.get('language', 'unknown') if doc.metadata else 'unknown'
metadata = doc.metadata.copy() if doc.metadata else {}
metadata['document_type'] = 'code_ast'
result_docs.extend(self._process_with_tree_sitter(code, language, metadata))
return result_docs
def _process_with_tree_sitter(self, code: str, language: str,
metadata: Dict[str, Any]) -> List[Document]:
def _ensure_language() -> None:
if language not in self._languages:
try:
from tree_sitter import Language
from importlib import import_module
module_name = f'tree_sitter_{language}'
lang_module = import_module(module_name)
self._languages[language] = Language(lang_module.language())
except ImportError:
raise ImportError(
f"Could not import {module_name}. Install with: pip install {module_name}")
_ensure_language()
result_docs: List[Document] = []
self._parser.language = self._languages[language]
tree = self._parser.parse(bytes(code, "utf8"))
ast_json: AstNode = self._convert_tree_to_json(tree.root_node, code)
features: CodeFeatures = self._extract_features(tree.root_node, code, language)
repr: CodeRepresentation = {
"ast": ast_json,
"features": features,
"language": language,
"code_length": len(code)
}
metadata['processing_method'] = 'tree_sitter'
ast_doc: Document = Document(
text=json.dumps(repr),
metadata=metadata
)
result_docs.append(ast_doc)
if len(code) > self.chunk_size:
chunk_docs = self._generate_code_chunks(
code, tree.root_node, language, metadata)
result_docs.extend(chunk_docs)
return result_docs
def _convert_tree_to_json(self, node, code: str, depth: int = 0) -> AstNode:
if depth > self.max_depth:
return cast(AstNode, {"type": "max_depth_reached"})
if not node:
return cast(AstNode, {})
start_byte, end_byte = node.start_byte, node.end_byte
text = code[start_byte:end_byte] if end_byte <= len(code) else ""
start_point: AstNodePoint = {"row": node.start_point[0], "column": node.start_point[1]}
end_point: AstNodePoint = {"row": node.end_point[0], "column": node.end_point[1]}
result: AstNode = {
"type": node.type,
"start_point": start_point,
"end_point": end_point,
"start_byte": start_byte,
"end_byte": end_byte
}
if len(text) < self.max_node_len or node.child_count == 0:
result["text"] = text
if node.child_count > 0:
children = []
for child in node.children:
child_json = self._convert_tree_to_json(child, code, depth + 1)
if child_json:
children.append(child_json)
result["children"] = children
return result
def _extract_features(self, node: Any, code: str, language: str) -> CodeFeatures:
features: CodeFeatures = {
"node_counts": self._count_node_types(node),
"code_metrics": self._calculate_code_metrics(code, language),
"identifier_count": 0,
"function_count": 0,
"class_count": 0,
"statement_count": 0
}
cursor = node.walk()
def _visit():
nonlocal features
current_node = cursor.node
if current_node.type == "identifier":
features["identifier_count"] += 1
elif current_node.type in ("function_definition", "method_definition", "function_declaration"):
features["function_count"] += 1
elif current_node.type in ("class_definition", "class_declaration"):
features["class_count"] += 1
elif "statement" in current_node.type:
features["statement_count"] += 1
if cursor.goto_first_child():
_visit()
cursor.goto_parent()
if cursor.goto_next_sibling():
_visit()
_visit()
return features
def _count_node_types(self, root_node) -> Dict[str, int]:
counts = {}
def _traverse(node):
if node.type not in counts:
counts[node.type] = 0
counts[node.type] += 1
for child in node.children:
_traverse(child)
_traverse(root_node)
return counts
def _calculate_code_metrics(self, code: str, language: str) -> CodeMetrics:
lines = code.splitlines()
code_lines = [line.strip() for line in lines if line.strip(
) and not line.strip().startswith(('#', '//', '/*', '*', '*/'))]
metrics: CodeMetrics = {
"line_count": len(lines),
"code_line_count": len(code_lines),
"avg_line_length": sum(len(line) for line in code_lines) / max(len(code_lines), 1),
"max_line_length": max([len(line) for line in code_lines]) if code_lines else 0,
"character_count": len(code)
}
return metrics
def _generate_code_chunks(
self,
code: str,
root_node,
language: str,
metadata: Dict[str, Any]) -> List[Document]:
chunks = []
lines = code.splitlines()
boundaries = []
def _collect_declarations(node, path=""):
if node.type in ("function_definition", "method_definition", "class_definition",
"function_declaration", "method_declaration", "class_declaration"):
start_line = node.start_point[0]
end_line = node.end_point[0]
if end_line - start_line >= 3:
node_type = "function" if "function" in node.type else "class"
name = None
for child in node.children:
if child.type == "identifier":
name = code[child.start_byte:child.end_byte]
break
boundary: CodeBoundary = {
"start": start_line,
"end": end_line,
"type": node_type,
"name": name,
"node": node
}
boundaries.append(boundary)
traverse_cursor = root_node.walk()
def _traverse_nodes():
current_node = traverse_cursor.node
_collect_declarations(current_node)
if traverse_cursor.goto_first_child():
_traverse_nodes()
traverse_cursor.goto_parent()
if traverse_cursor.goto_next_sibling():
_traverse_nodes()
_traverse_nodes()
if boundaries:
for boundary in boundaries:
start_line = boundary["start"]
end_line = boundary["end"]
if end_line - start_line < 3:
continue
chunk_code = "\n".join(lines[start_line:end_line + 1])
chunk_metadata = metadata.copy()
chunk_metadata["chunk_type"] = boundary["type"]
chunk_metadata["chunk_name"] = boundary["name"]
chunk_metadata["start_line"] = start_line
chunk_metadata["end_line"] = end_line
chunk_metadata["document_type"] = "code_chunk"
try:
tree = self._parser.parse(bytes(chunk_code, "utf8"))
ast_json = self._convert_tree_to_json(tree.root_node, chunk_code)
representation: ChunkRepresentation = {
"ast": ast_json,
"code": chunk_code,
"language": language,
"name": boundary["name"],
"type": boundary["type"]
}
chunk_doc = Document(
text=json.dumps(representation),
metadata=chunk_metadata
)
chunks.append(chunk_doc)
except BaseException:
chunk_metadata["ast_available"] = False
chunks.append(Document(text=chunk_code, metadata=chunk_metadata))
if len(chunks) < 2 and len(lines) > self.chunk_size:
for i in range(0, len(lines), self.chunk_size - self.chunk_overlap):
end_idx = min(i + self.chunk_size, len(lines))
chunk_code = "\n".join(lines[i:end_idx])
chunk_metadata = metadata.copy()
chunk_metadata["chunk_type"] = "window"
chunk_metadata["start_line"] = i
chunk_metadata["end_line"] = end_idx - 1
chunk_metadata["document_type"] = "code_chunk"
chunks.append(Document(text=chunk_code, metadata=chunk_metadata))
if end_idx >= len(lines):
break
return chunks
def _initialize_by_component_configer(
self, doc_processor_configer: ComponentConfiger) -> 'DocProcessor':
super()._initialize_by_component_configer(doc_processor_configer)
try:
from tree_sitter import Parser
self._parser = Parser()
self._languages = {}
except ImportError:
raise ImportError(
"tree-sitter not available. Install with: pip install tree-sitter")
if hasattr(doc_processor_configer, "max_depth"):
self.max_depth = doc_processor_configer.max_depth
if not hasattr(doc_processor_configer, "language_dir"):
raise ValueError(
"language_dir is required - tree-sitter needs compiled language libraries (.so files) to parse code, download from https://tree-sitter.github.io/tree-sitter/#available-parsers")
self.language_dir = doc_processor_configer.language_dir
if hasattr(doc_processor_configer, "chunk_size"):
self.chunk_size = doc_processor_configer.chunk_size
if hasattr(doc_processor_configer, "chunk_overlap"):
self.chunk_overlap = doc_processor_configer.chunk_overlap
if hasattr(doc_processor_configer, "max_node_text_length"):
self.max_node_len = doc_processor_configer.max_node_len
return self
@@ -0,0 +1,461 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/12/04 00:00
# @Author : AI Assistant
# @Email : ai@example.com
# @FileName: contract_clause_fragmenter.py
import re
import logging
from typing import List, Optional, Dict, Tuple, Any
from dataclasses import dataclass
from datetime import datetime
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import DocProcessor
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
logger = logging.getLogger(__name__)
@dataclass
class ClauseNode:
"""Represents a clause in the contract hierarchy.
Attributes:
id: Unique identifier for the clause.
text: Content of the clause.
clause_type: Type of clause (article, section, subsection, etc.).
hierarchy_level: Depth in the hierarchy (0 for top-level).
parent_id: ID of parent clause (None for top-level).
children_ids: IDs of child clauses.
position: Position in the original document.
"""
id: str
text: str
clause_type: str
hierarchy_level: int
parent_id: Optional[str] = None
children_ids: List[str] = None
position: int = 0
def __post_init__(self):
if self.children_ids is None:
self.children_ids = []
class ContractClauseFragmenter(DocProcessor):
"""Fragment legal contracts by individual clauses while preserving hierarchy.
This processor parses legal contracts and fragments them into individual clauses
based on common legal formatting patterns. It preserves the hierarchical structure
(Article → Section → Subsection) and creates separate documents for each clause
with rich metadata about relationships and dependencies.
Attributes:
preserve_hierarchy: Whether to preserve and track clause hierarchy.
clause_patterns: List of regex patterns for detecting clauses.
min_clause_length: Minimum length for a valid clause (characters).
extract_references: Whether to extract cross-references between clauses.
skip_on_error: Whether to skip documents that fail processing.
"""
preserve_hierarchy: bool = True
clause_patterns: List[str] = None
min_clause_length: int = 10
extract_references: bool = True
skip_on_error: bool = True
def __init__(self, **data):
super().__init__(**data)
if self.clause_patterns is None:
self.clause_patterns = [
r'^Article\s+[IVX\d]+\.?\s*',
r'^ARTICLE\s+[IVX\d]+\.?\s*',
r'^Section\s+\d+(\.\d+)*\.?\s*',
r'^SECTION\s+\d+(\.\d+)*\.?\s*',
r'^\d+(\.\d+)*\.?\s+', # Fixed: makes trailing dot optional
r'^第[一二三四五六七八九十百千\d]+条\s*', # Chinese: 第X条
r'^[一二三四五六七八九十百千\d]+、\s*', # Chinese enumeration
]
def _process_docs(self, origin_docs: List[Document], query: Query = None) -> List[Document]:
"""Fragment documents into individual clauses.
Args:
origin_docs: List of contract documents to fragment.
query: Optional query object (not used in this processor).
Returns:
List of clause documents with hierarchy metadata.
"""
if not origin_docs:
return []
logger.info(f"Starting clause fragmentation of {len(origin_docs)} documents")
all_clause_docs = []
for doc in origin_docs:
try:
clause_docs = self._fragment_document(doc)
all_clause_docs.extend(clause_docs)
logger.info(f"Fragmented document {doc.id} into {len(clause_docs)} clauses")
except Exception as e:
logger.error(f"Failed to fragment document {doc.id}: {e}")
if not self.skip_on_error:
raise
# Pass through original document if skip_on_error is True
all_clause_docs.append(doc)
logger.info(f"Total clauses created: {len(all_clause_docs)}")
return all_clause_docs
def _fragment_document(self, doc: Document) -> List[Document]:
"""Fragment a single document into clauses.
Args:
doc: Document to fragment.
Returns:
List of clause documents.
"""
text = doc.text
# Step 1: Detect clause boundaries
boundaries = self._detect_clause_boundaries(text)
if not boundaries:
logger.warning(f"No clauses detected in document {doc.id}, returning as single clause")
return [self._create_single_clause_doc(doc, text, 0)]
# Step 2: Extract clause texts
clauses = self._extract_clauses(text, boundaries)
# Step 3: Build hierarchy if enabled
if self.preserve_hierarchy:
hierarchy = self._parse_hierarchy(clauses)
else:
hierarchy = {}
# Step 4: Create documents for each clause
clause_docs = self._create_clause_documents(doc, clauses, hierarchy)
return clause_docs
def _detect_clause_boundaries(self, text: str) -> List[Tuple[int, int, str, str]]:
"""Detect clause boundaries in the text.
Args:
text: Contract text to analyze.
Returns:
List of tuples: (start_pos, end_pos, clause_type, clause_id).
"""
boundaries = []
lines = text.split('\n')
current_pos = 0
for line_idx, line in enumerate(lines):
line_stripped = line.strip()
if not line_stripped:
current_pos += len(line) + 1 # +1 for newline
continue
# Check each pattern
for pattern in self.clause_patterns:
match = re.match(pattern, line_stripped, re.IGNORECASE)
if match:
# Determine clause type and ID
clause_type, clause_id = self._parse_clause_header(line_stripped)
# Find the end of this clause (start of next clause or end of text)
end_pos = self._find_clause_end(lines, line_idx + 1, current_pos + len(line))
boundaries.append((current_pos, end_pos, clause_type, clause_id))
break
current_pos += len(line) + 1 # +1 for newline
return boundaries
def _find_clause_end(self, lines: List[str], start_line_idx: int, start_pos: int) -> int:
"""Find the end position of a clause.
Args:
lines: All text lines.
start_line_idx: Line index to start searching from.
start_pos: Character position to start from.
Returns:
End position of the clause.
"""
current_pos = start_pos
for line_idx in range(start_line_idx, len(lines)):
line = lines[line_idx]
# Check if this line starts a new clause
for pattern in self.clause_patterns:
if re.match(pattern, line.strip(), re.IGNORECASE):
return current_pos
current_pos += len(line) + 1 # +1 for newline
# Reached end of document
return current_pos
def _parse_clause_header(self, header: str) -> Tuple[str, str]:
"""Parse clause header to extract type and ID.
Args:
header: Clause header string.
Returns:
Tuple of (clause_type, clause_id).
"""
header = header.strip()
# Article patterns
if re.match(r'^(Article|ARTICLE)\s+', header, re.IGNORECASE):
match = re.search(r'[IVX\d]+', header)
clause_id = match.group(0) if match else 'unknown'
return ('article', f'article_{clause_id}')
# Section patterns
if re.match(r'^(Section|SECTION)\s+', header, re.IGNORECASE):
match = re.search(r'\d+(\.\d+)*', header)
clause_id = match.group(0) if match else 'unknown'
return ('section', f'section_{clause_id}')
# Numbered patterns
match = re.match(r'^(\d+(\.\d+)*)', header)
if match:
clause_id = match.group(1)
level = clause_id.count('.')
clause_type = f'subsection_level_{level}'
return (clause_type, f'clause_{clause_id}')
# Chinese patterns
if re.match(r'^第[一二三四五六七八九十百千\d]+条', header):
match = re.search(r'第(.+?)条', header)
clause_id = match.group(1) if match else 'unknown'
return ('article', f'article_{clause_id}')
# Fallback
return ('clause', 'clause_unknown')
def _extract_clauses(self, text: str, boundaries: List[Tuple[int, int, str, str]]) -> List[ClauseNode]:
"""Extract clause nodes from boundaries.
Args:
text: Full contract text.
boundaries: List of clause boundaries.
Returns:
List of ClauseNode objects.
"""
clauses = []
for idx, (start, end, clause_type, clause_id) in enumerate(boundaries):
clause_text = text[start:end].strip()
if len(clause_text) < self.min_clause_length:
logger.debug(f"Skipping short clause: {clause_id} (length: {len(clause_text)})")
continue
clause_node = ClauseNode(
id=clause_id,
text=clause_text,
clause_type=clause_type,
hierarchy_level=0, # Will be determined in hierarchy parsing
position=idx
)
clauses.append(clause_node)
return clauses
def _parse_hierarchy(self, clauses: List[ClauseNode]) -> Dict[str, ClauseNode]:
"""Parse hierarchical relationships between clauses.
Args:
clauses: List of clause nodes.
Returns:
Dictionary mapping clause IDs to updated ClauseNode objects.
"""
hierarchy: Dict[str, ClauseNode] = {}
for clause in clauses:
hierarchy[clause.id] = clause
# Determine hierarchy levels and parent-child relationships
for i, clause in enumerate(clauses):
# Determine hierarchy level based on clause type
if clause.clause_type == 'article':
clause.hierarchy_level = 0
elif clause.clause_type == 'section':
clause.hierarchy_level = 1
elif clause.clause_type.startswith('subsection_level_'):
level = int(clause.clause_type.split('_')[-1])
clause.hierarchy_level = 2 + level
else:
clause.hierarchy_level = 2
# Find parent clause
if i > 0 and clause.hierarchy_level > 0:
# Look backwards for parent
for j in range(i - 1, -1, -1):
prev_clause = clauses[j]
if prev_clause.hierarchy_level < clause.hierarchy_level:
clause.parent_id = prev_clause.id
prev_clause.children_ids.append(clause.id)
break
return hierarchy
def _create_clause_documents(self, original_doc: Document, clauses: List[ClauseNode],
hierarchy: Dict[str, ClauseNode]) -> List[Document]:
"""Create Document objects for each clause.
Args:
original_doc: Original contract document.
clauses: List of clause nodes.
hierarchy: Clause hierarchy mapping.
Returns:
List of clause documents.
"""
clause_docs = []
for clause in clauses:
# Build metadata
metadata = {
'processor_name': self.name,
'processor_version': '1.0',
'processing_timestamp': datetime.now().isoformat(),
'source_document_id': original_doc.id,
'clause_id': clause.id,
'clause_type': clause.clause_type,
'hierarchy_level': clause.hierarchy_level,
'position': clause.position,
}
# Add original metadata
if original_doc.metadata:
metadata['original_metadata'] = original_doc.metadata
# Add hierarchy information
if self.preserve_hierarchy:
metadata['parent_clause'] = clause.parent_id
metadata['children_clauses'] = clause.children_ids
# Extract references if enabled
if self.extract_references:
references = self._extract_references(clause.text, clauses)
if references:
metadata['clause_references'] = references
# Create document
doc = Document(
text=clause.text,
metadata=metadata,
keywords=original_doc.keywords
)
clause_docs.append(doc)
return clause_docs
def _extract_references(self, text: str, all_clauses: List[ClauseNode]) -> List[str]:
"""Extract cross-references to other clauses.
Args:
text: Clause text.
all_clauses: All clauses in the document.
Returns:
List of referenced clause IDs.
"""
references = []
# Common reference patterns
patterns = [
r'(Article|ARTICLE)\s+([IVX\d]+)',
r'(Section|SECTION)\s+(\d+(\.\d+)*)',
r'clause\s+(\d+(\.\d+)*)',
r'第(.+?)条', # Chinese
]
for pattern in patterns:
matches = re.finditer(pattern, text, re.IGNORECASE)
for match in matches:
ref_text = match.group(0)
# Try to find matching clause
for clause in all_clauses:
if ref_text.lower() in clause.text.lower()[:100]: # Check beginning of clause
if clause.id not in references:
references.append(clause.id)
return references
def _create_single_clause_doc(self, original_doc: Document, text: str, position: int) -> Document:
"""Create a single clause document when no structure is detected.
Args:
original_doc: Original document.
text: Clause text.
position: Position index.
Returns:
Clause document.
"""
metadata = {
'processor_name': self.name,
'processor_version': '1.0',
'processing_timestamp': datetime.now().isoformat(),
'source_document_id': original_doc.id,
'clause_id': 'single_clause',
'clause_type': 'unstructured',
'hierarchy_level': 0,
'position': position,
}
if original_doc.metadata:
metadata['original_metadata'] = original_doc.metadata
return Document(
text=text,
metadata=metadata,
keywords=original_doc.keywords
)
def _initialize_by_component_configer(self,
doc_processor_configer: ComponentConfiger) -> 'ContractClauseFragmenter':
"""Initialize fragmenter parameters from configuration.
Args:
doc_processor_configer: Configuration object containing fragmenter parameters.
Returns:
Initialized document processor instance.
"""
super()._initialize_by_component_configer(doc_processor_configer)
if hasattr(doc_processor_configer, "preserve_hierarchy"):
self.preserve_hierarchy = doc_processor_configer.preserve_hierarchy
if hasattr(doc_processor_configer, "clause_patterns"):
self.clause_patterns = doc_processor_configer.clause_patterns
if hasattr(doc_processor_configer, "min_clause_length"):
self.min_clause_length = doc_processor_configer.min_clause_length
if hasattr(doc_processor_configer, "extract_references"):
self.extract_references = doc_processor_configer.extract_references
if hasattr(doc_processor_configer, "skip_on_error"):
self.skip_on_error = doc_processor_configer.skip_on_error
return self
@@ -0,0 +1,18 @@
name: 'contract_clause_fragmenter'
description: 'Fragment legal contracts by individual clauses while preserving hierarchical structure'
preserve_hierarchy: true
min_clause_length: 10
extract_references: true
skip_on_error: true
clause_patterns:
- '^Article\s+[IVX\d]+\.?\s*'
- '^ARTICLE\s+[IVX\d]+\.?\s*'
- '^Section\s+\d+(\.\d+)*\.?\s*'
- '^SECTION\s+\d+(\.\d+)*\.?\s*'
- '^\d+\.(\d+\.)*\s+'
- '^第[一二三四五六七八九十百千\d]+条\s*'
- '^[一二三四五六七八九十百千\d]+、\s*'
metadata:
type: 'DOC_PROCESSOR'
module: 'agentuniverse.agent.action.knowledge.doc_processor.contract_clause_fragmenter'
class: 'ContractClauseFragmenter'
@@ -0,0 +1,96 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/8/5 15:48
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: dashscope_reranker.py
from typing import List, Optional
import dashscope
from http import HTTPStatus
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import \
DocProcessor
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.config.component_configer.component_configer import \
ComponentConfiger
MODEL_NAME_MAP = {
"gte_rerank": dashscope.TextReRank.Models.gte_rerank
}
class DashscopeReranker(DocProcessor):
"""Document reranker using Dashscope's TextReRank API.
This processor reranks documents based on their relevance to a query
using Dashscope's text reranking models.
Attributes:
model_name: The name of the reranking model to use.
top_n: Maximum number of documents to return after reranking.
"""
model_name: str = "gte_rerank"
top_n: int = 10
def _process_docs(self, origin_docs: List[Document], query: Query = None) -> \
List[Document]:
"""Rerank documents based on their relevance to the query.
Args:
origin_docs: List of documents to be reranked.
query: Query object containing the search query string.
Returns:
List[Document]: Reranked documents sorted by relevance score.
Raises:
Exception: If query is missing or API call fails.
"""
if not query or not query.query_str:
raise Exception("Dashscope reranker need an origin string query.")
if len(origin_docs)<1:
return origin_docs
documents_texts = []
for _doc in origin_docs:
documents_texts.append(_doc.text)
resp = dashscope.TextReRank.call(
model=MODEL_NAME_MAP.get(self.model_name),
query=query.query_str,
documents=documents_texts,
top_n=self.top_n,
return_documents=False
)
if resp.status_code == HTTPStatus.OK:
results = resp.output.results
else:
raise Exception(f"Dashscope rerank api call error: {resp}")
rerank_docs = []
for _result in results:
index = _result.index
if origin_docs[index].metadata:
origin_docs[index].metadata["relevance_score"] = _result.relevance_score
else:
origin_docs[index].metadata = {"relevance_score": _result.relevance_score}
rerank_docs.append(origin_docs[index])
return rerank_docs
def _initialize_by_component_configer(self,
doc_processor_configer: ComponentConfiger) -> 'DocProcessor':
"""Initialize reranker parameters from component configuration.
Args:
doc_processor_configer: Configuration object containing reranker parameters.
Returns:
DocProcessor: The initialized document processor instance.
"""
super()._initialize_by_component_configer(doc_processor_configer)
if hasattr(doc_processor_configer, "model_name"):
self.model_name = doc_processor_configer.model_name
if hasattr(doc_processor_configer, "top_n"):
self.top_n = doc_processor_configer.top_n
return self
@@ -0,0 +1,6 @@
name: 'dashscope_reranker'
description: 'reranker use dashscope api'
metadata:
type: 'DOC_PROCESSOR'
module: 'agentuniverse.agent.action.knowledge.doc_processor.dashscope_reranker'
class: 'DashscopeReranker'
@@ -0,0 +1,78 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/7/23 14:00
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: doc_processor.py
from abc import abstractmethod
from typing import List, Optional
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.base.component.component_base import ComponentEnum
from agentuniverse.base.component.component_base import ComponentBase
from agentuniverse.base.config.component_configer.component_configer import \
ComponentConfiger
class DocProcessor(ComponentBase):
"""The basic class for doc processor.
DocProcessor is an abstract base class that defines the interface for document
processing components in the agentUniverse framework. Document processors can
transform, filter, or enhance documents before they are used by agents.
Attributes:
component_type: Enum value identifying this as a document processor component.
name: Optional name identifier for the processor.
description: Optional description of the processor's functionality.
"""
component_type: ComponentEnum = ComponentEnum.DOC_PROCESSOR
name: Optional[str] = None
description: Optional[str] = None
class Config:
arbitrary_types_allowed = True
def process_docs(self, origin_docs: List[Document], query: Query = None) -> \
List[Document]:
"""Process input documents,return should also be a document list."""
return self._process_docs(origin_docs, query)
@abstractmethod
def _process_docs(self, origin_docs: List[Document],
query: Query = None) -> \
List[Document]:
"""Process input documents,return should also be a document list.
This is the core implementation method that subclasses must override to
provide specific document processing logic. The method should transform
the input documents according to the processor's purpose and optionally
use the query for context-aware processing.
Args:
origin_docs: List of documents to be processed.
query: Optional query object that may influence the processing.
Returns:
List[Document]: Processed documents.
"""
pass
def _initialize_by_component_configer(self,
doc_processor_configer: ComponentConfiger) \
-> 'DocProcessor':
"""Initialize the DocProcessor by the ComponentConfiger object.
Args:
doc_processor_configer(ComponentConfiger): A configer contains DocProcessor
basic info.
Returns:
DocProcessor: A DocProcessor instance.
"""
self.name = doc_processor_configer.name
self.description = doc_processor_configer.description
return self
@@ -0,0 +1,20 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/7/23 14:12
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: doc_processor_manager.py
from agentuniverse.base.annotation.singleton import singleton
from agentuniverse.base.component.component_enum import ComponentEnum
from agentuniverse.base.component.component_manager_base import ComponentManagerBase
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import DocProcessor
@singleton
class DocProcessorManager(ComponentManagerBase[DocProcessor]):
"""A singleton manager class of the DocProcessor."""
def __init__(self):
super().__init__(ComponentEnum.DOC_PROCESSOR)
@@ -0,0 +1,677 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/12/04 00:00
# @Author : AI Assistant
# @Email : ai@example.com
# @FileName: financial_event_aggregator.py
import hashlib
import logging
from typing import List, Optional, Dict, Any, Set
from dataclasses import dataclass, field
from datetime import datetime
import numpy as np
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import DocProcessor
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.agent.action.knowledge.embedding.embedding_manager import EmbeddingManager
from agentuniverse.llm.llm_manager import LLMManager
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
logger = logging.getLogger(__name__)
@dataclass
class EventCluster:
"""Represents a cluster of related news articles about the same event.
Attributes:
event_id: Unique identifier for the event.
event_type: Type of event (merger, acquisition, earnings, etc.).
documents: List of document IDs in this cluster.
representative_doc: Most representative document in cluster.
entities_involved: Key entities mentioned across documents.
publication_dates: List of publication dates.
"""
event_id: str
event_type: str
documents: List[str] = field(default_factory=list)
representative_doc: Optional[Document] = None
entities_involved: Set[str] = field(default_factory=set)
publication_dates: List[str] = field(default_factory=list)
class FinancialEventAggregator(DocProcessor):
"""Aggregate related financial news articles into unified event reports.
This processor:
1. Clusters semantically similar articles using embeddings
2. Identifies event types (merger, acquisition, earnings, etc.)
3. Generates multi-document summaries
4. Tracks source attribution and credibility
Attributes:
similarity_threshold: Similarity threshold for clustering (0.0-1.0).
use_embeddings: Whether to use embeddings for similarity.
embedding_name: Name of embedding model to use.
clustering_method: Clustering algorithm ('dbscan', 'hierarchical').
summarization_mode: Summarization mode ('extractive', 'map_reduce').
use_llm: Whether to use LLM for summarization.
llm_name: Name of LLM to use.
max_sources_per_event: Maximum number of sources to include per event.
preserve_sources: Whether to preserve source document references.
skip_on_error: Whether to skip documents that fail processing.
"""
similarity_threshold: float = 0.85
use_embeddings: bool = True
embedding_name: Optional[str] = None
clustering_method: str = 'dbscan' # 'dbscan' or 'hierarchical'
summarization_mode: str = 'map_reduce' # 'extractive' or 'map_reduce'
use_llm: bool = True
llm_name: Optional[str] = None
max_sources_per_event: int = 20
preserve_sources: bool = True
skip_on_error: bool = True
def _process_docs(self, origin_docs: List[Document], query: Query = None) -> List[Document]:
"""Aggregate related financial news into event documents.
Args:
origin_docs: List of news article documents.
query: Optional query object (not used in this processor).
Returns:
List of aggregated event documents.
"""
if not origin_docs:
return []
logger.info(f"Starting financial event aggregation for {len(origin_docs)} documents")
# Step 1: Compute similarity matrix
similarity_matrix = self._compute_similarity_matrix(origin_docs)
# Step 2: Cluster related documents
clusters = self._cluster_related_documents(origin_docs, similarity_matrix)
logger.info(f"Identified {len(clusters)} event clusters")
# Step 3: Process each cluster
aggregated_docs = []
for cluster in clusters:
try:
event_doc = self._aggregate_cluster(cluster, origin_docs)
aggregated_docs.append(event_doc)
except Exception as e:
logger.error(f"Failed to aggregate cluster {cluster.event_id}: {e}")
if not self.skip_on_error:
raise
logger.info(f"Created {len(aggregated_docs)} aggregated event documents")
return aggregated_docs
def _compute_similarity_matrix(self, docs: List[Document]) -> np.ndarray:
"""Compute pairwise similarity matrix for documents.
Args:
docs: List of documents.
Returns:
Similarity matrix (n x n numpy array).
"""
n = len(docs)
similarity_matrix = np.zeros((n, n))
if not self.use_embeddings or not self.embedding_name:
logger.warning("Embeddings not enabled, using text overlap similarity")
return self._compute_text_similarity_matrix(docs)
try:
# Get embedding model
embedding_manager = EmbeddingManager()
embedding_model = embedding_manager.get_instance_obj(self.embedding_name)
# Compute embeddings
texts = [doc.text for doc in docs]
embeddings = embedding_model.get_embeddings(texts)
# Update document embeddings
for doc, embedding in zip(docs, embeddings):
doc.embedding = embedding
# Compute similarity matrix
for i in range(n):
for j in range(i, n):
if i == j:
similarity_matrix[i][j] = 1.0
else:
sim = self._cosine_similarity(embeddings[i], embeddings[j])
similarity_matrix[i][j] = sim
similarity_matrix[j][i] = sim
except Exception as e:
logger.error(f"Failed to compute embeddings: {e}")
# Fallback to text similarity
return self._compute_text_similarity_matrix(docs)
return similarity_matrix
def _cosine_similarity(self, vec1: List[float], vec2: List[float]) -> float:
"""Compute cosine similarity between two vectors.
Args:
vec1: First vector.
vec2: Second vector.
Returns:
Cosine similarity score.
"""
dot_product = sum(a * b for a, b in zip(vec1, vec2))
magnitude1 = sum(a * a for a in vec1) ** 0.5
magnitude2 = sum(b * b for b in vec2) ** 0.5
if magnitude1 == 0 or magnitude2 == 0:
return 0.0
return dot_product / (magnitude1 * magnitude2)
def _compute_text_similarity_matrix(self, docs: List[Document]) -> np.ndarray:
"""Compute similarity matrix using text overlap (fallback method).
Args:
docs: List of documents.
Returns:
Similarity matrix.
"""
n = len(docs)
similarity_matrix = np.zeros((n, n))
for i in range(n):
for j in range(i, n):
if i == j:
similarity_matrix[i][j] = 1.0
else:
# Simple word overlap similarity
words_i = set(docs[i].text.lower().split())
words_j = set(docs[j].text.lower().split())
overlap = len(words_i & words_j)
union = len(words_i | words_j)
sim = overlap / union if union > 0 else 0.0
similarity_matrix[i][j] = sim
similarity_matrix[j][i] = sim
return similarity_matrix
def _cluster_related_documents(self, docs: List[Document],
similarity_matrix: np.ndarray) -> List[EventCluster]:
"""Cluster related documents based on similarity.
Args:
docs: List of documents.
similarity_matrix: Pairwise similarity matrix.
Returns:
List of EventCluster objects.
"""
if self.clustering_method == 'dbscan':
return self._cluster_with_dbscan(docs, similarity_matrix)
elif self.clustering_method == 'hierarchical':
return self._cluster_with_hierarchical(docs, similarity_matrix)
else:
logger.warning(f"Unknown clustering method: {self.clustering_method}, using dbscan")
return self._cluster_with_dbscan(docs, similarity_matrix)
def _cluster_with_dbscan(self, docs: List[Document],
similarity_matrix: np.ndarray) -> List[EventCluster]:
"""Cluster documents using DBSCAN.
Args:
docs: List of documents.
similarity_matrix: Similarity matrix.
Returns:
List of EventCluster objects.
"""
# Convert similarity to distance
distance_matrix = 1 - similarity_matrix
# Simple DBSCAN-like clustering
n = len(docs)
clusters = []
visited = set()
eps = 1 - self.similarity_threshold
for i in range(n):
if i in visited:
continue
# Find neighbors
neighbors = [j for j in range(n) if distance_matrix[i][j] < eps and j != i]
if len(neighbors) < 1:
# Singleton cluster
cluster = self._create_cluster([docs[i]])
clusters.append(cluster)
visited.add(i)
else:
# Expand cluster
cluster_docs = [docs[i]]
visited.add(i)
queue = neighbors.copy()
while queue:
j = queue.pop(0)
if j in visited:
continue
visited.add(j)
cluster_docs.append(docs[j])
# Find neighbors of j
j_neighbors = [k for k in range(n) if distance_matrix[j][k] < eps and k != j]
queue.extend([k for k in j_neighbors if k not in visited])
cluster = self._create_cluster(cluster_docs)
clusters.append(cluster)
return clusters
def _cluster_with_hierarchical(self, docs: List[Document],
similarity_matrix: np.ndarray) -> List[EventCluster]:
"""Cluster documents using hierarchical clustering.
Args:
docs: List of documents.
similarity_matrix: Similarity matrix.
Returns:
List of EventCluster objects.
"""
# Simple agglomerative clustering
n = len(docs)
clusters_list = [[i] for i in range(n)] # Start with each doc in its own cluster
while len(clusters_list) > 1:
# Find most similar pair of clusters
max_sim = -1
merge_i, merge_j = -1, -1
for i in range(len(clusters_list)):
for j in range(i + 1, len(clusters_list)):
# Average linkage
sim = np.mean([similarity_matrix[doc_i][doc_j]
for doc_i in clusters_list[i]
for doc_j in clusters_list[j]])
if sim > max_sim:
max_sim = sim
merge_i, merge_j = i, j
# Stop if similarity below threshold
if max_sim < self.similarity_threshold:
break
# Merge clusters
clusters_list[merge_i].extend(clusters_list[merge_j])
del clusters_list[merge_j]
# Create EventCluster objects
clusters = []
for cluster_indices in clusters_list:
cluster_docs = [docs[i] for i in cluster_indices]
cluster = self._create_cluster(cluster_docs)
clusters.append(cluster)
return clusters
def _create_cluster(self, cluster_docs: List[Document]) -> EventCluster:
"""Create EventCluster from list of documents.
Args:
cluster_docs: Documents in the cluster.
Returns:
EventCluster object.
"""
# Generate event ID
event_id = self._generate_event_id(cluster_docs)
# Identify event type
event_type = self._identify_event_type(cluster_docs)
# Extract entities
entities = self._extract_entities(cluster_docs)
# Find representative document (longest or most central)
representative_doc = max(cluster_docs, key=lambda d: len(d.text))
# Extract publication dates
pub_dates = []
for doc in cluster_docs:
if doc.metadata and 'publication_date' in doc.metadata:
pub_dates.append(doc.metadata['publication_date'])
cluster = EventCluster(
event_id=event_id,
event_type=event_type,
documents=[doc.id for doc in cluster_docs],
representative_doc=representative_doc,
entities_involved=entities,
publication_dates=pub_dates
)
return cluster
def _generate_event_id(self, docs: List[Document]) -> str:
"""Generate unique event ID for a cluster.
Args:
docs: Documents in cluster.
Returns:
Event ID string.
"""
# Create hash from sorted document IDs
doc_ids = sorted([doc.id for doc in docs])
hash_input = '|'.join(doc_ids)
event_hash = hashlib.md5(hash_input.encode()).hexdigest()[:12]
return f"event_{event_hash}"
def _identify_event_type(self, docs: List[Document]) -> str:
"""Identify the type of financial event.
Args:
docs: Documents in cluster.
Returns:
Event type string.
"""
# Combine text from all documents
combined_text = ' '.join([doc.text[:500] for doc in docs]) # Use first 500 chars
text_lower = combined_text.lower()
# Event type patterns
event_patterns = {
'merger': ['merger', 'merge', 'acquisition', 'acquire', '并购', '收购'],
'earnings': ['earnings', 'quarterly results', 'financial results', '财报', '业绩'],
'ipo': ['ipo', 'initial public offering', 'going public', '上市'],
'lawsuit': ['lawsuit', 'litigation', 'sued', '诉讼'],
'bankruptcy': ['bankruptcy', 'chapter 11', 'insolvency', '破产'],
'partnership': ['partnership', 'collaboration', 'joint venture', '合作'],
'product_launch': ['product launch', 'new product', 'release', '发布'],
'leadership_change': ['ceo', 'cfo', 'resignation', 'appointed', '任命'],
}
# Count matches for each event type
type_scores = {}
for event_type, keywords in event_patterns.items():
score = sum(1 for keyword in keywords if keyword in text_lower)
if score > 0:
type_scores[event_type] = score
# Return type with highest score
if type_scores:
return max(type_scores, key=type_scores.get)
else:
return 'general_news'
def _extract_entities(self, docs: List[Document]) -> Set[str]:
"""Extract key entities mentioned across documents.
Args:
docs: Documents in cluster.
Returns:
Set of entity names.
"""
entities = set()
# Simple extraction: look for capitalized words
import re
for doc in docs:
# Extract capitalized phrases (potential company/person names)
matches = re.findall(r'\b[A-Z][a-z]+(?:\s+[A-Z][a-z]+)*\b', doc.text)
entities.update(matches[:10]) # Limit to avoid too many
return entities
def _aggregate_cluster(self, cluster: EventCluster, all_docs: List[Document]) -> Document:
"""Aggregate a cluster into a single event document.
Args:
cluster: EventCluster to aggregate.
all_docs: All original documents.
Returns:
Aggregated event document.
"""
# Get cluster documents
cluster_docs = [doc for doc in all_docs if doc.id in cluster.documents]
# Limit sources if needed
if len(cluster_docs) > self.max_sources_per_event:
cluster_docs = cluster_docs[:self.max_sources_per_event]
# Generate summary
if self.use_llm and self.llm_name:
summary = self._generate_llm_summary(cluster_docs, cluster)
else:
summary = self._generate_extractive_summary(cluster_docs)
# Detect conflicts
conflicts = self._detect_conflicts(cluster_docs)
# Score credibility
credibility_scores = self._score_credibility(cluster_docs)
# Create aggregated document
aggregated_doc = self._create_aggregated_document(
cluster, cluster_docs, summary, conflicts, credibility_scores
)
return aggregated_doc
def _generate_llm_summary(self, docs: List[Document], cluster: EventCluster) -> str:
"""Generate summary using LLM.
Args:
docs: Documents to summarize.
cluster: Event cluster information.
Returns:
Summary text.
"""
try:
llm_manager = LLMManager()
llm = llm_manager.get_instance_obj(self.llm_name)
# Combine document texts
combined_text = '\n\n---\n\n'.join([doc.text[:1000] for doc in docs])
# Build prompt
prompt = f"""Summarize the following news articles about a {cluster.event_type} event.
Create a comprehensive summary that:
1. Describes the main event
2. Includes key facts and figures
3. Mentions main entities involved
4. Notes any conflicting information
Articles:
{combined_text[:5000]}
Summary:"""
messages = [{"role": "user", "content": prompt}]
summary = llm.call(messages=messages)
return summary
except Exception as e:
logger.error(f"LLM summarization failed: {e}")
return self._generate_extractive_summary(docs)
def _generate_extractive_summary(self, docs: List[Document]) -> str:
"""Generate extractive summary (fallback method).
Args:
docs: Documents to summarize.
Returns:
Summary text.
"""
# Simple extractive: concatenate first sentences from each document
summary_parts = []
for doc in docs[:5]: # Limit to first 5 docs
# Extract first sentence
first_sentence = doc.text.split('.')[0] + '.'
if len(first_sentence) > 20:
summary_parts.append(first_sentence)
summary = ' '.join(summary_parts)
return summary[:1000] # Limit length
def _detect_conflicts(self, docs: List[Document]) -> List[Dict[str, Any]]:
"""Detect conflicting information across documents.
Args:
docs: Documents to analyze.
Returns:
List of detected conflicts.
"""
# Simplified conflict detection
conflicts = []
# Check for contradictory statements (future enhancement)
# For now, just note if there are multiple sources
if len(docs) > 3:
conflicts.append({
'type': 'multiple_sources',
'description': f'{len(docs)} different sources report on this event',
'severity': 'info'
})
return conflicts
def _score_credibility(self, docs: List[Document]) -> Dict[str, float]:
"""Score credibility of source documents.
Args:
docs: Documents to score.
Returns:
Dictionary mapping document IDs to credibility scores.
"""
scores = {}
for doc in docs:
# Simple heuristic: longer documents are more credible
score = min(1.0, len(doc.text) / 1000)
# Boost score if metadata indicates verified source
if doc.metadata and doc.metadata.get('verified_source'):
score = min(1.0, score * 1.2)
scores[doc.id] = score
return scores
def _create_aggregated_document(self, cluster: EventCluster,
source_docs: List[Document],
summary: str,
conflicts: List[Dict[str, Any]],
credibility_scores: Dict[str, float]) -> Document:
"""Create aggregated event document.
Args:
cluster: Event cluster.
source_docs: Source documents.
summary: Generated summary.
conflicts: Detected conflicts.
credibility_scores: Credibility scores.
Returns:
Aggregated document.
"""
# Build metadata
metadata = {
'processor_name': self.name,
'processor_version': '1.0',
'processing_timestamp': datetime.now().isoformat(),
'event_id': cluster.event_id,
'event_type': cluster.event_type,
'entities_involved': list(cluster.entities_involved),
'source_count': len(source_docs),
'aggregated_summary': summary,
}
# Add source references if enabled
if self.preserve_sources:
source_refs = []
for doc in source_docs:
source_refs.append({
'id': doc.id,
'credibility_score': credibility_scores.get(doc.id, 0.5),
'publication_date': doc.metadata.get('publication_date') if doc.metadata else None
})
metadata['source_documents'] = source_refs
# Add conflicts
if conflicts:
metadata['conflicting_info'] = conflicts
# Add publication dates
if cluster.publication_dates:
metadata['publication_dates'] = cluster.publication_dates
# Create keywords
keywords = set(['financial_event', cluster.event_type])
keywords.update(cluster.entities_involved)
# Create aggregated document
aggregated_doc = Document(
text=summary,
metadata=metadata,
keywords=keywords
)
return aggregated_doc
def _initialize_by_component_configer(self,
doc_processor_configer: ComponentConfiger) -> 'FinancialEventAggregator':
"""Initialize aggregator parameters from configuration.
Args:
doc_processor_configer: Configuration object.
Returns:
Initialized document processor instance.
"""
super()._initialize_by_component_configer(doc_processor_configer)
if hasattr(doc_processor_configer, "similarity_threshold"):
self.similarity_threshold = doc_processor_configer.similarity_threshold
if hasattr(doc_processor_configer, "use_embeddings"):
self.use_embeddings = doc_processor_configer.use_embeddings
if hasattr(doc_processor_configer, "embedding_name"):
self.embedding_name = doc_processor_configer.embedding_name
if hasattr(doc_processor_configer, "clustering_method"):
self.clustering_method = doc_processor_configer.clustering_method
if hasattr(doc_processor_configer, "summarization_mode"):
self.summarization_mode = doc_processor_configer.summarization_mode
if hasattr(doc_processor_configer, "use_llm"):
self.use_llm = doc_processor_configer.use_llm
if hasattr(doc_processor_configer, "llm_name"):
self.llm_name = doc_processor_configer.llm_name
if hasattr(doc_processor_configer, "max_sources_per_event"):
self.max_sources_per_event = doc_processor_configer.max_sources_per_event
if hasattr(doc_processor_configer, "preserve_sources"):
self.preserve_sources = doc_processor_configer.preserve_sources
if hasattr(doc_processor_configer, "skip_on_error"):
self.skip_on_error = doc_processor_configer.skip_on_error
return self
@@ -0,0 +1,16 @@
name: 'financial_event_aggregator'
description: 'Aggregate related financial news articles into unified event reports with multi-document summarization'
similarity_threshold: 0.85
use_embeddings: true
embedding_name: 'default_embedding'
clustering_method: 'dbscan' # Options: 'dbscan', 'hierarchical'
summarization_mode: 'map_reduce' # Options: 'extractive', 'map_reduce'
use_llm: true
llm_name: 'default_llm'
max_sources_per_event: 20
preserve_sources: true
skip_on_error: true
metadata:
type: 'DOC_PROCESSOR'
module: 'agentuniverse.agent.action.knowledge.doc_processor.financial_event_aggregator'
class: 'FinancialEventAggregator'
@@ -0,0 +1,686 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/12/04 00:00
# @Author : AI Assistant
# @Email : ai@example.com
# @FileName: financial_indicator_extractor.py
import re
import logging
from typing import List, Optional, Dict, Any, Tuple
from dataclasses import dataclass
from datetime import datetime
from decimal import Decimal
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import DocProcessor
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
logger = logging.getLogger(__name__)
@dataclass
class FinancialMetric:
"""Represents a financial metric extracted from text.
Attributes:
name: Metric name (e.g., 'revenue', 'profit').
value: Numeric value.
unit: Unit of measurement (e.g., 'USD', 'million').
time_period: Time period (e.g., 'Q1 2024', 'FY2023').
context: Surrounding text context.
position: Position in document.
confidence: Extraction confidence score.
raw_match: Original matched text for precise currency detection.
"""
name: str
value: float
unit: str
time_period: Optional[str] = None
context: str = ""
position: int = 0
confidence: float = 1.0
raw_match: str = ""
@dataclass
class Comparison:
"""Represents a comparative metric (e.g., YoY growth).
Attributes:
metric_name: Name of the metric being compared.
current_value: Current period value.
previous_value: Previous period value.
change: Absolute change.
change_percent: Percentage change.
comparison_type: Type of comparison (YoY, QoQ, etc.).
"""
metric_name: str
current_value: float
previous_value: float
change: float
change_percent: float
comparison_type: str
class FinancialIndicatorExtractor(DocProcessor):
"""Extract financial indicators and metrics from financial reports.
This processor extracts structured financial information including:
1. Financial metrics (revenue, profit, margins, ratios)
2. Temporal context (quarters, fiscal years)
3. Comparative analysis (YoY, QoQ growth rates)
4. Currency normalization
Attributes:
metrics: List of metric names to extract.
extract_temporal: Whether to extract time period information.
extract_comparisons: Whether to extract comparative metrics.
currency_normalization: Whether to normalize currency values.
use_llm: Whether to use LLM for enhanced extraction.
llm_name: Name of the LLM to use.
skip_on_error: Whether to skip documents that fail processing.
"""
metrics: List[str] = None
extract_temporal: bool = True
extract_comparisons: bool = True
currency_normalization: bool = True
use_llm: bool = False
llm_name: Optional[str] = None
skip_on_error: bool = True
def __init__(self, **data):
super().__init__(**data)
if self.metrics is None:
self.metrics = [
'revenue', 'sales', 'income',
'profit', 'earnings', 'ebitda',
'gross_margin', 'operating_margin', 'net_margin', 'margin', # Specific margins before general
'eps', 'earnings_per_share',
'roi', 'return_on_investment', 'roe', 'roa',
'debt', 'debt_ratio', 'leverage',
'cash_flow', 'free_cash_flow',
'assets', 'liabilities', 'equity',
'growth_rate', 'market_share', 'churn_rate', # Added percentage metrics
]
def _process_docs(self, origin_docs: List[Document], query: Query = None) -> List[Document]:
"""Extract financial indicators from documents.
Args:
origin_docs: List of financial report documents.
query: Optional query object (not used in this processor).
Returns:
List of documents with extracted financial metrics.
"""
if not origin_docs:
return []
logger.info(f"Starting financial indicator extraction from {len(origin_docs)} documents")
processed_docs = []
for doc in origin_docs:
try:
enhanced_doc = self._extract_from_document(doc)
processed_docs.append(enhanced_doc)
logger.info(f"Extracted metrics from document {doc.id}")
except Exception as e:
logger.error(f"Failed to extract from document {doc.id}: {e}")
if not self.skip_on_error:
raise
# Pass through original document if skip_on_error is True
processed_docs.append(doc)
logger.info(f"Financial extraction complete for {len(processed_docs)} documents")
return processed_docs
def _extract_from_document(self, doc: Document) -> Document:
"""Extract financial metrics from a single document.
Args:
doc: Financial report document.
Returns:
Document with extracted metrics in metadata.
"""
text = doc.text
# Step 1: Extract financial metrics
metrics = self._extract_metrics(text)
logger.debug(f"Extracted {len(metrics)} metrics")
# Step 2: Extract temporal context
time_periods = []
if self.extract_temporal:
time_periods = self._extract_time_periods(text)
# Associate time periods with metrics
for metric in metrics:
metric.time_period = self._find_nearest_time_period(
metric.position, time_periods, text
)
# Step 3: Extract comparisons
comparisons = []
if self.extract_comparisons:
comparisons = self._detect_comparisons(text, metrics)
logger.debug(f"Detected {len(comparisons)} comparisons")
# Step 4: Normalize currency if enabled
if self.currency_normalization:
self._normalize_currencies(metrics)
# Step 5: Create enhanced document with metadata
enhanced_doc = self._create_enhanced_document(doc, metrics, comparisons)
return enhanced_doc
def _extract_metrics(self, text: str) -> List[FinancialMetric]:
"""Extract financial metrics from text.
Args:
text: Financial report text.
Returns:
List of extracted FinancialMetric objects.
"""
metrics = []
# Define metric patterns (comprehensive)
metric_patterns = {
'revenue': [
r'revenue[s]?\s*(?:of\s+|was\s+|reached\s+|totaled\s+|:\s*)?[\$€£¥]?(-?[0-9,.]+)\s*(million|billion|M|B|千万|亿)?',
r'sales\s*(?:of\s+|was\s+|reached\s+|totaled\s+|:\s*)?[\$€£¥]?(-?[0-9,.]+)\s*(million|billion|M|B|千万|亿)?',
r'total\s+revenue\s*(?:of\s+|:\s*|for\s+[A-Z0-9\s]+)?(?:reached\s+|was\s+|totaled\s+)?[\$€£¥]?(-?[0-9,.]+)\s*(million|billion|M|B)?',
r'营收[达到]?(-?[0-9,.]+)\s*(万|亿)?',
r'[\$€£¥](-?[0-9,.]+)\s*(?:million|billion|M|B)\s+(?:in\s+)?revenue',
],
'sales': [
r'sales\s*(?:of\s+|was\s+|reached\s+|totaled\s+|:\s*)?[\$€£¥]?(-?[0-9,.]+)\s*(million|billion|M|B|千万|亿)?',
],
'income': [
r'(?:net\s+)?income\s*(?:of\s+|was\s+|:\s*)?[\$€£¥]?(-?[0-9,.]+)\s*(million|billion|M|B)?',
],
'profit': [
r'(?:net\s+|gross\s+|operating\s+)?profit\s*(?:of\s+|was\s+|reached\s+|:\s*)?[\$€£¥]?(-?[0-9,.]+)\s*(million|billion|M|B|千万|亿)?',
r'(?:net\s+|operating\s+)?(?:loss|losses)\s*(?:of\s+|:\s*)?[\$€£¥]?(-?[0-9,.]+)\s*(million|billion|M|B)?',
r'earnings\s*(?:of\s+|was\s+|reached\s+|:\s*)?[\$€£¥]?(-?[0-9,.]+)\s*(million|billion|M|B|千万|亿)?',
r'净利润(?:达到)?[\$€£¥]?(-?[0-9,.]+)\s*(万|亿)?',
r'(?:negative|loss)(?:\s+of)?\s*[\$€£¥]?(-?[0-9,.]+)\s*(million|billion|M|B)?',
r'\(-?[\$€£¥]?([0-9,.]+)\s*(million|billion|M|B)?\)', # Negative in parentheses
],
'margin': [
r'(?:gross|operating|net)?\s*margin[:]?\s+(?:of\s+|was\s+)?(-?[0-9,.]+)%',
r'(?:gross|operating|net)?\s*margin\s+(?:reached\s+)?(-?[0-9,.]+)%',
r'利润率(-?[0-9,.]+)%',
],
'gross_margin': [
r'gross\s+margin[:]?\s+(-?[0-9,.]+)%',
],
'operating_margin': [
r'operating\s+margin[:]?\s+(-?[0-9,.]+)%',
],
'net_margin': [
r'net\s+(?:profit\s+)?margin[:]?\s+(-?[0-9,.]+)%',
],
'eps': [
r'(?:diluted\s+)?(?:earnings|EPS)\s+per\s+share\s*(?:of\s+|was\s+|reached\s+|:\s*)?[\$€£¥]?(-?[0-9,.]+)',
r'EPS\s*(?:of\s+|was\s+|reached\s+|:\s*)?[\$€£¥]?(-?[0-9,.]+)',
r'diluted\s+EPS\s*(?:of\s+|was\s+|reached\s+|:\s*)?[\$€£¥]?(-?[0-9,.]+)',
r'每股收益(-?[0-9,.]+)',
],
'earnings_per_share': [
r'earnings\s+per\s+share[:]?\s+[\$€£¥]?(-?[0-9,.]+)',
],
'cash_flow': [
r'(?:operating\s+|free\s+)?cash\s+flow\s+(?:of\s+)?[\$€£¥]?(-?[0-9,.]+)\s*(million|billion|M|B|千万|亿)?',
r'现金流(-?[0-9,.]+)\s*(万|亿)?',
],
'free_cash_flow': [
r'free\s+cash\s+flow[:]?\s+[\$€£¥]?(-?[0-9,.]+)\s*(million|billion|M|B)?',
],
'roi': [
r'(?:return\s+on\s+investment|ROI)[:]?\s+(-?[0-9,.]+)%',
],
'roe': [
r'(?:return\s+on\s+equity|ROE)[:]?\s+(-?[0-9,.]+)%',
],
'roa': [
r'(?:return\s+on\s+assets|ROA)[:]?\s+(-?[0-9,.]+)%',
],
'debt': [
r'(?:total\s+)?debt[:]?\s+[\$€£¥]?(-?[0-9,.]+)\s*(million|billion|M|B)?',
],
'debt_ratio': [
r'debt[- ]to[- ]equity\s+ratio[:]?\s+(-?[0-9,.]+)',
r'debt\s+ratio[:]?\s+(-?[0-9,.]+)',
],
'assets': [
r'(?:total\s+)?assets[:]?\s+[\$€£¥]?(-?[0-9,.]+)\s*(million|billion|M|B)?',
],
'liabilities': [
r'(?:total\s+)?liabilities[:]?\s+[\$€£¥]?(-?[0-9,.]+)\s*(million|billion|M|B)?',
],
'equity': [
r'(?:shareholders?\s+)?equity[:]?\s+[\$€£¥]?(-?[0-9,.]+)\s*(million|billion|M|B)?',
],
# Generic percentage-based metrics
'growth_rate': [
r'growth\s+rate[:]?\s+(-?[0-9,.]+)%',
],
'market_share': [
r'market\s+share[:]?\s+(-?[0-9,.]+)%',
],
'churn_rate': [
r'churn\s+rate[:]?\s+(-?[0-9,.]+)%',
],
}
# Extract metrics using patterns
for metric_name in self.metrics:
patterns = metric_patterns.get(metric_name, [])
for pattern in patterns:
matches = re.finditer(pattern, text, re.IGNORECASE)
for match in matches:
try:
value_str = match.group(1).replace(',', '')
value = float(value_str)
# Check if in parentheses (accounting negative)
full_match = match.group(0)
if full_match.startswith('(') and full_match.endswith(')'):
value = -abs(value)
# Check for explicit "loss" or "negative" keywords
elif 'loss' in full_match.lower() or 'negative' in full_match.lower():
value = -abs(value)
# Get unit if available
unit = match.group(2) if len(match.groups()) > 1 else ''
# Convert based on unit
value = self._convert_unit_to_base(value, unit)
# Get context
start = max(0, match.start() - 50)
end = min(len(text), match.end() + 50)
context = text[start:end]
metric = FinancialMetric(
name=metric_name,
value=value,
unit='USD', # Default, will be normalized
context=context,
position=match.start(),
raw_match=full_match # Store original matched text
)
metrics.append(metric)
except (ValueError, IndexError) as e:
logger.debug(f"Failed to parse metric: {e}")
continue
return metrics
def _convert_unit_to_base(self, value: float, unit: str) -> float:
"""Convert value based on unit to base unit.
Args:
value: Numeric value.
unit: Unit string.
Returns:
Converted value in base unit.
"""
unit_lower = unit.lower() if unit else ''
multipliers = {
'million': 1_000_000,
'billion': 1_000_000_000,
'm': 1_000_000,
'b': 1_000_000_000,
'千万': 10_000_000,
'亿': 100_000_000,
'万': 10_000,
}
multiplier = multipliers.get(unit_lower, 1.0)
return value * multiplier
def _extract_time_periods(self, text: str) -> List[Tuple[str, int]]:
"""Extract time period references from text.
Args:
text: Financial report text.
Returns:
List of (time_period, position) tuples.
"""
time_periods = []
# Time period patterns
patterns = [
r'(Q[1-4]\s+20\d{2})', # Q1 2024
r'(FY\s*20\d{2})', # FY2023
r'(fiscal\s+year\s+20\d{2})', # fiscal year 2023
r'(20\d{2}\s+Q[1-4])', # 2024 Q1
r'(第[一二三四]季度\s*20\d{2})', # Chinese: 第一季度 2024
r'(20\d{2}年度)', # Chinese: 2024年度
]
for pattern in patterns:
matches = re.finditer(pattern, text, re.IGNORECASE)
for match in matches:
time_periods.append((match.group(1), match.start()))
return time_periods
def _find_nearest_time_period(self, position: int,
time_periods: List[Tuple[str, int]],
text: str) -> Optional[str]:
"""Find the nearest time period to a given position.
Args:
position: Position in text.
time_periods: List of (time_period, position) tuples.
text: Full text.
Returns:
Nearest time period string or None.
"""
if not time_periods:
return None
# Find nearest time period (within 200 characters)
nearest = None
min_distance = float('inf')
for period, period_pos in time_periods:
distance = abs(position - period_pos)
if distance < min_distance and distance < 200:
min_distance = distance
nearest = period
return nearest
def _detect_comparisons(self, text: str, metrics: List[FinancialMetric]) -> List[Comparison]:
"""Detect comparative metrics (YoY, QoQ).
Args:
text: Financial report text.
metrics: Extracted metrics.
Returns:
List of Comparison objects.
"""
comparisons = []
# Enhanced comparison patterns for YoY and QoQ
comparison_patterns = [
# YoY patterns
(r'([0-9,.]+)%?\s+(?:YoY|year-over-year|year-on-year)', 'yoy'),
(r'(?:YoY|year-over-year|year-on-year)\s+(?:growth|increase|up|decline|decrease|down)\s+(?:of\s+)?([0-9,.]+)%?', 'yoy'),
(r'(?:growth|increase|up|rose)\s+([0-9,.]+)%?\s+(?:YoY|year-over-year|year-on-year)', 'yoy'),
(r'([a-zA-Z\s]+)\s+up\s+([0-9,.]+)%\s+year-over-year', 'yoy'),
(r'同比增长([0-9,.]+)%?', 'yoy'),
# QoQ patterns
(r'([0-9,.]+)%?\s+(?:QoQ|quarter-over-quarter|quarter-on-quarter)', 'qoq'),
(r'(?:QoQ|quarter-over-quarter|quarter-on-quarter)\s+(?:growth|increase|up|decline|decrease|down)\s+(?:of\s+)?([0-9,.]+)%?', 'qoq'),
(r'(?:growth|increase|up|rose)\s+([0-9,.]+)%?\s+(?:QoQ|quarter-over-quarter|quarter-on-quarter)', 'qoq'),
(r'环比增长([0-9,.]+)%?', 'qoq'),
# General comparison patterns (try to infer type from context)
(r'([0-9,.]+)%?\s+(?:increase|growth|up|higher)\s+(?:compared to|vs\.?|versus|over)', 'unknown'),
(r'(?:increased|grew|rose)\s+by\s+([0-9,.]+)%', 'unknown'),
]
for pattern, comp_type in comparison_patterns:
matches = re.finditer(pattern, text, re.IGNORECASE)
for match in matches:
try:
# Extract the percentage value (might be in group 1 or 2)
change_percent_str = None
for i in range(1, match.lastindex + 1 if match.lastindex else 1):
try:
val = match.group(i)
if val and re.match(r'^[0-9,.]+$', val):
change_percent_str = val
break
except:
continue
if not change_percent_str:
continue
change_percent = float(change_percent_str.replace(',', ''))
# Determine comparison type (use pattern's type if not unknown)
comparison_type = comp_type
if comparison_type == 'unknown':
# Try to infer from context
match_text = match.group(0).lower()
if 'yoy' in match_text or 'year' in match_text or '同比' in match_text:
comparison_type = 'yoy'
elif 'qoq' in match_text or 'quarter' in match_text or '环比' in match_text:
comparison_type = 'qoq'
# Find associated metric
metric_name = self._find_associated_metric(match.start(), metrics)
comparison = Comparison(
metric_name=metric_name or 'general',
current_value=0.0, # Would need more context to extract
previous_value=0.0,
change=0.0,
change_percent=change_percent,
comparison_type=comparison_type
)
comparisons.append(comparison)
except (ValueError, IndexError) as e:
logger.debug(f"Failed to parse comparison: {e}")
continue
return comparisons
def _find_associated_metric(self, position: int, metrics: List[FinancialMetric]) -> Optional[str]:
"""Find the metric associated with a comparison.
Args:
position: Position of comparison in text.
metrics: List of extracted metrics.
Returns:
Metric name or None.
"""
# Find nearest metric (within 100 characters)
nearest_metric = None
min_distance = float('inf')
for metric in metrics:
distance = abs(position - metric.position)
if distance < min_distance and distance < 100:
min_distance = distance
nearest_metric = metric.name
return nearest_metric
def _normalize_currencies(self, metrics: List[FinancialMetric]) -> None:
"""Normalize currency values to a standard currency.
Args:
metrics: List of financial metrics.
Note:
Modifies metrics in place. Currently uses fixed exchange rates.
"""
# Fixed exchange rates (simplified)
exchange_rates = {
'CNY': 0.14, # CNY to USD
'EUR': 1.09, # EUR to USD
'GBP': 1.27, # GBP to USD
'JPY': 0.0067, # JPY to USD
}
for metric in metrics:
# Check context for currency indicators
if '¥' in metric.context or '元' in metric.context or 'CNY' in metric.context:
metric.value *= exchange_rates.get('CNY', 1.0)
metric.unit = 'USD'
elif '€' in metric.context or 'EUR' in metric.context:
metric.value *= exchange_rates.get('EUR', 1.0)
metric.unit = 'USD'
elif '£' in metric.context or 'GBP' in metric.context:
metric.value *= exchange_rates.get('GBP', 1.0)
metric.unit = 'USD'
def _create_enhanced_document(self, original_doc: Document,
metrics: List[FinancialMetric],
comparisons: List[Comparison]) -> Document:
"""Create enhanced document with financial metrics in metadata.
Args:
original_doc: Original document.
metrics: Extracted metrics.
comparisons: Detected comparisons.
Returns:
Enhanced document with financial metadata.
"""
# Build metadata
metadata = original_doc.metadata.copy() if original_doc.metadata else {}
# Save original metadata
metadata['original_metadata'] = original_doc.metadata.copy() if original_doc.metadata else {}
metadata.update({
'processor_name': self.name,
'processor_version': '1.0',
'processing_timestamp': datetime.now().isoformat(),
'source_document_id': original_doc.id,
})
# Group financial metrics by metric name
financial_metrics = {}
for metric in metrics:
if metric.name not in financial_metrics:
financial_metrics[metric.name] = []
financial_metrics[metric.name].append({
'value': metric.value,
'unit': metric.unit,
'time_period': metric.time_period,
'confidence': metric.confidence,
'context': metric.context[:100] if len(metric.context) > 100 else metric.context,
'currency': self._detect_currency(metric.raw_match if metric.raw_match else metric.context),
'scale': self._detect_scale(metric.context),
})
metadata['financial_metrics'] = financial_metrics
metadata['metric_count'] = len(metrics)
# Add comparisons
comparative_metrics = []
if comparisons:
for comp in comparisons:
comparative_metrics.append({
'metric': comp.metric_name,
'change_percent': comp.change_percent,
'comparison_type': comp.comparison_type,
})
if comparative_metrics:
metadata['comparative_metrics'] = comparative_metrics
# Add keywords
keywords = original_doc.keywords.copy() if original_doc.keywords else set()
for metric in metrics:
keywords.add(metric.name)
if comparisons:
keywords.add('comparative_analysis')
# Create enhanced document
enhanced_doc = Document(
id=original_doc.id,
text=original_doc.text,
metadata=metadata,
embedding=original_doc.embedding,
keywords=keywords
)
return enhanced_doc
def _detect_currency(self, context: str) -> str:
"""Detect currency from context.
Args:
context: Text context.
Returns:
Currency code or empty string.
"""
if '$' in context or 'USD' in context:
return 'USD'
elif '€' in context or 'EUR' in context:
return 'EUR'
elif '£' in context or 'GBP' in context:
return 'GBP'
elif '¥' in context or 'CNY' in context or '元' in context:
return 'CNY'
return 'USD' # Default
def _detect_scale(self, context: str) -> str:
"""Detect scale from context.
Args:
context: Text context.
Returns:
Scale indicator.
"""
context_lower = context.lower()
if 'billion' in context_lower or ' b' in context_lower or '亿' in context:
return 'billion'
elif 'million' in context_lower or ' m' in context_lower or '千万' in context or '百万' in context:
return 'million'
elif 'thousand' in context_lower or '千' in context:
return 'thousand'
return 'units'
def _initialize_by_component_configer(self,
doc_processor_configer: ComponentConfiger) -> 'FinancialIndicatorExtractor':
"""Initialize extractor parameters from configuration.
Args:
doc_processor_configer: Configuration object containing extractor parameters.
Returns:
Initialized document processor instance.
"""
super()._initialize_by_component_configer(doc_processor_configer)
if hasattr(doc_processor_configer, "metrics"):
self.metrics = doc_processor_configer.metrics
if hasattr(doc_processor_configer, "extract_temporal"):
self.extract_temporal = doc_processor_configer.extract_temporal
if hasattr(doc_processor_configer, "extract_comparisons"):
self.extract_comparisons = doc_processor_configer.extract_comparisons
if hasattr(doc_processor_configer, "currency_normalization"):
self.currency_normalization = doc_processor_configer.currency_normalization
if hasattr(doc_processor_configer, "use_llm"):
self.use_llm = doc_processor_configer.use_llm
if hasattr(doc_processor_configer, "llm_name"):
self.llm_name = doc_processor_configer.llm_name
if hasattr(doc_processor_configer, "skip_on_error"):
self.skip_on_error = doc_processor_configer.skip_on_error
return self
@@ -0,0 +1,34 @@
name: 'financial_indicator_extractor'
description: 'Extract financial indicators from reports including metrics, temporal context, and comparisons'
extract_temporal: true
extract_comparisons: true
currency_normalization: true
use_llm: false
skip_on_error: true
metrics:
- revenue
- sales
- income
- profit
- earnings
- ebitda
- margin
- gross_margin
- operating_margin
- net_margin
- eps
- earnings_per_share
- roi
- return_on_investment
- debt
- debt_ratio
- leverage
- cash_flow
- free_cash_flow
- assets
- liabilities
- equity
metadata:
type: 'DOC_PROCESSOR'
module: 'agentuniverse.agent.action.knowledge.doc_processor.financial_indicator_extractor'
class: 'FinancialIndicatorExtractor'
@@ -0,0 +1,155 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/8/28 16:54
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: hierarchical_regex_text_splitter.py
import re
import uuid
from typing import List, Optional
from agentuniverse.agent.agent_manager import AgentManager
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import \
DocProcessor
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.config.component_configer.component_configer import \
ComponentConfiger
class HierarchicalRegexTextSplitter(DocProcessor):
"""Splits text into hierarchical structure based on regex patterns."""
merge_first: bool = False
hierarchical_index: List[dict] = [
{
"reg_exp": "第[零一二三四五六七八九十百千]+章",
"need_summary": True
},
{
"reg_exp": "第[零一二三四五六七八九十百千]+节",
"need_summary": False
}
]
summary_agent: str = "simple_summary_agent"
llm: Optional[dict] = None
def _hierarchical_split_single_doc(self, doc: Document) -> List[Document]:
"""Splits a single document into hierarchical structure using regex patterns.
Args:
doc: Document to be split hierarchically.
Returns:
List of hierarchically structured documents.
"""
hierarchy = {}
levels = [(f"item_{i}", re.compile(index['reg_exp'])) for i, index in enumerate(self.hierarchical_index)]
current_level = {level[0]: None for level in levels}
current_level['root'] = None
root = Document(
text='',
metadata={
'hierarchical_parent': 'root'
}
)
hierarchy['root'] = root
last_inserted_id = 'root'
# build hierarchical doc tree
for line in doc.text.splitlines():
line = line.strip()
if not line:
continue
for level_name, pattern in levels:
match = pattern.match(line)
if match:
_ptr = levels.index((level_name, pattern))
parent_level = \
levels[_ptr - 1][0] if _ptr > 0 else 'root'
parent_id = current_level[parent_level].id if \
current_level[parent_level] else 'root'
# use uuid4 to generate a random id, because chapter name can always duplicate
node = Document(
id=str(uuid.uuid4()),
text=line,
metadata={
'hierarchical_parent': parent_id,
'hierarchical_info': match.group(0) if match else '',
'hierarchical_level': _ptr
}
)
hierarchy[node.id] = node
current_level[level_name] = node
last_inserted_id = node.id
break
else:
hierarchy[last_inserted_id].text += "\n" + line
# Append text to the last inserted node's text and all its parent
_inserted_id = hierarchy[last_inserted_id].metadata['hierarchical_parent']
while _inserted_id != 'root':
hierarchy[_inserted_id].text += "\n" + line
_inserted_id = hierarchy[_inserted_id].metadata['hierarchical_parent']
hierarchy.pop("root")
hierarchical_docs = []
# summary the text if docs hierarchical_level need summary
for k, v in hierarchy.items():
hierarchical_level = v.metadata['hierarchical_level']
if self.hierarchical_index[hierarchical_level]['need_summary']:
agent = AgentManager().get_instance_obj(self.summary_agent)
if self.llm:
agent.agent_model.profile['llm_model'] = self.llm
else:
agent.agent_model.profile['llm_model'] = {
"name": "__default_instance__"}
agent_result = agent.run(input=v.text)
v.text = agent_result.output
hierarchical_docs.append(v)
return hierarchical_docs
def _process_docs(self, origin_docs: List[Document], query: Query = None) -> \
List[Document]:
"""Processes documents by splitting them into hierarchical structure.
Args:
origin_docs: List of documents to be processed.
query: Optional query object (not used in this processor).
Returns:
List of hierarchically structured documents.
"""
# merge all documents first
merged_docs = origin_docs
if self.merge_first and len(origin_docs) > 0:
for _doc in origin_docs[1:]:
origin_docs[0].text += "\n" + _doc.text
merged_docs = [origin_docs[0]]
hierarchical_docs = []
for _doc in merged_docs:
hierarchical_docs.extend(self._hierarchical_split_single_doc(_doc))
return hierarchical_docs
def _initialize_by_component_configer(self,
doc_processor_configer: ComponentConfiger) -> 'DocProcessor':
"""Initializes the splitter with configuration parameters.
Args:
doc_processor_configer: Configuration object containing splitter parameters.
Returns:
Initialized document processor instance.
"""
super()._initialize_by_component_configer(doc_processor_configer)
if hasattr(doc_processor_configer, "hierarchical_index"):
self.hierarchical_index = doc_processor_configer.hierarchical_index
if hasattr(doc_processor_configer, "merge_first"):
self.merge_first = doc_processor_configer.merge_first
if hasattr(doc_processor_configer, "llm"):
self.llm = doc_processor_configer.llm
if hasattr(doc_processor_configer, "summary_agent"):
self.summary_agent = doc_processor_configer.summary_agent
return self
@@ -0,0 +1,92 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/8/6 10:44
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: jieba_keyword_extractor.py
from typing import List
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import \
DocProcessor
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.config.component_configer.component_configer import \
ComponentConfiger
import jieba
import jieba.analyse
# nltk english stopwords
stop_words = {'or', "mustn't", 'how', 'their', 'again', 'few', 'other', 'who',
'being', 'theirs', 'during', 'if', 'on', 'she', 'wouldn', 'why',
'above', 'll', "weren't", 'your', 'are', 'an', 'over', 'his',
'hasn', 'off', 'you', 'he', 'was', "you'd", 'me', 'ain', 'any',
'what', 'most', 're', 'haven', "isn't", 'there', "it's", 'same',
'm', 'only', 'my', 'needn', 'too', 'into', 'in', 'by', 'between',
"that'll", "mightn't", "aren't", 'am', 'up', 'having', "you'll",
"you're", 'these', 'mustn', 'himself', 'down', 'such', 'wasn',
'ourselves', 'did', 'because', 'should', 'won', 'about', 'aren',
'don', 'while', 't', 'isn', 'have', 'whom', 'myself', 'itself',
'this', 'will', 'and', 'further', 'no', 'where', 'ma', 'yours',
'been', "didn't", 'that', 'had', 'when', 'we', 'herself', 'some',
'has', "she's", "needn't", "should've", 'of', "won't", 'both',
'which', "haven't", 'yourself', 'through', 'the', 'from',
"you've", 'for', 'then', 'hadn', 'a', 'them', 'as', 'after',
'themselves', "shouldn't", 'they', 'y', 'doesn', 'didn', 'here',
'ours', 'own', 'it', "hadn't", 'each', 'our', 'shouldn', 'all',
'out', 'before', 'couldn', 'd', "doesn't", 'hers', "hasn't",
'than', 'at', "don't", 'not', 'to', 'is', 'with', 'until',
'does', 'yourselves', 'under', 'below', 'i', 'those', "wouldn't",
'once', "couldn't", 'just', 's', 'shan', "wasn't", 'him', 'so',
'can', 'doing', 'o', 'her', 'were', 'now', 'very', 'weren',
'its', 'against', 'do', 've', 'be', 'mightn', 'but', "shan't",
'nor', 'more'}
chinese_stopwords = {'的', '了', '在', '是', '我', '有', '和', '就', '不',
'人', '都', '一', '一个', '上', '也', '很', '到', '说',
'要', '去', '你', '会', '着', '没有', '看', '好', '自己',
'请问', '您', '他', '于', '及', '即', '为', '最', '从', '以',
'了', '将', '与', '吗', '吧', '中', '#', '什么', '怎么', '哪个',
'哪些', '啥', '相关'}
class JiebaKeywordExtractor(DocProcessor):
"""Extracts keywords from documents using Jieba Chinese text segmentation."""
top_k: int = 3
def _process_docs(self, origin_docs: List[Document], query: Query = None) \
-> List[Document]:
"""Extracts top keywords from documents after filtering stopwords.
Args:
origin_docs: List of documents to extract keywords from.
query: Optional query object (not used in this processor).
Returns:
The original documents with keywords added to their metadata.
"""
for _doc in origin_docs:
words = jieba.lcut(_doc.text)
filtered_words = [word for word in words if word not in
chinese_stopwords and word.lower() not in stop_words]
keywords = jieba.analyse.extract_tags(" ".join(filtered_words),
topK=self.top_k)
_doc.keywords.update(keywords)
return origin_docs
def _initialize_by_component_configer(self,
doc_processor_configer: ComponentConfiger) -> 'DocProcessor':
"""Initializes the extractor with configuration parameters.
Args:
doc_processor_configer: Configuration object containing extractor parameters.
Returns:
Initialized document processor instance.
"""
super()._initialize_by_component_configer(doc_processor_configer)
if hasattr(doc_processor_configer, "top_k"):
self.top_k = doc_processor_configer.top_k
return self
@@ -0,0 +1,7 @@
name: 'jieba_keyword_extractor'
description: 'extract keywords from text'
top_k: 3
metadata:
type: 'DOC_PROCESSOR'
module: 'agentuniverse.agent.action.knowledge.doc_processor.jieba_keyword_extractor'
class: 'JiebaKeywordExtractor'
@@ -0,0 +1,107 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2025/8/10 23:00
# @Author : xmhu2001
# @Email : xmhu2001@qq.com
# @FileName: jina_reranker.py
from typing import List, Optional
import requests
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import DocProcessor
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
from agentuniverse.base.util.env_util import get_from_env
api_base = "https://api.jina.ai/v1/rerank"
class JinaReranker(DocProcessor):
"""Document reranker using Jina AI's Rerank API.
This processor reranks documents based on their relevance to a query
using Jina AI's reranking models.
"""
api_key: Optional[str] = None
model_name: str = "jina-reranker-v2-base-multilingual"
top_n: int = 10
def _process_docs(self, origin_docs: List[Document], query: Query = None) -> List[Document]:
"""Rerank documents based on their relevance to the query.
Args:
origin_docs: List of documents to be reranked.
query: Query object containing the search query string.
Returns:
List[Document]: Reranked documents sorted by relevance score.
Raises:
Exception: If the query is missing, the API key is not set, or the API call fails.
"""
if not query or not query.query_str:
raise Exception("Jina AI reranker needs an origin string query.")
if not self.api_key:
raise Exception(
"Jina AI API key is not set. Please configure it in the component or environment variables.")
if not origin_docs:
return []
headers = {
"Content-Type": "application/json",
"Authorization": f"Bearer {self.api_key}",
}
payload = {
"model": self.model_name,
"query": query.query_str,
"documents": [doc.text for doc in origin_docs],
"top_n": self.top_n,
}
try:
response = requests.post(api_base, headers=headers, json=payload)
response.raise_for_status()
results = response.json().get("results", [])
except requests.exceptions.RequestException as e:
raise Exception(f"Jina AI rerank API call error: {e}")
rerank_docs = []
for result in results:
index = result.get("index")
relevance_score = result.get("relevance_score")
if index is None or relevance_score is None:
continue
if origin_docs[index].metadata:
origin_docs[index].metadata["relevance_score"] = relevance_score
else:
origin_docs[index].metadata = {"relevance_score": relevance_score}
rerank_docs.append(origin_docs[index])
return rerank_docs
def _initialize_by_component_configer(self, doc_processor_configer: ComponentConfiger) -> 'DocProcessor':
"""Initialize reranker parameters from component configuration.
Args:
doc_processor_configer: Configuration object for the doc processor.
Returns:
DocProcessor: The initialized document processor instance.
"""
super()._initialize_by_component_configer(doc_processor_configer)
self.api_key = get_from_env("JINA_API_KEY")
if hasattr(doc_processor_configer, "api_key"):
self.api_key = doc_processor_configer.api_key
if hasattr(doc_processor_configer, "model_name"):
self.model_name = doc_processor_configer.model_name
if hasattr(doc_processor_configer, "top_n"):
self.top_n = doc_processor_configer.top_n
return self
@@ -0,0 +1,6 @@
name: 'jina_reranker'
description: 'reranker use jina api'
metadata:
type: 'DOC_PROCESSOR'
module: 'agentuniverse.agent.action.knowledge.doc_processor.jina_reranker'
class: 'JinaReranker'
@@ -0,0 +1,75 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
from typing import List
# @Time : 2024/7/31 16:19
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: recursive_character_text_splitter.py
from typing import List, Optional
from langchain.text_splitter import RecursiveCharacterTextSplitter as Splitter
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import \
DocProcessor
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.config.component_configer.component_configer import \
ComponentConfiger
class RecursiveCharacterTextSplitter(DocProcessor):
"""Splits text recursively using a hierarchy of character separators."""
chunk_size: int = 200
chunk_overlap: int = 20
separators: List[str] = ["\n\n", "\n", " ", ""]
__splitter: Optional[Splitter] = None
@property
def splitter(self) -> Splitter:
if not self.__splitter:
self.__splitter = Splitter(separators=self.separators,
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap)
return self.__splitter
def _process_docs(self, origin_docs: List[Document], query: Query = None) -> \
List[Document]:
"""Split documents recursively using character separators.
Args:
origin_docs: List of documents to be split.
query: Optional query object (not used in this processor).
Returns:
List of split document chunks.
"""
lc_doc_list = self.splitter.split_documents(Document.as_langchain_list(
origin_docs
))
return Document.from_langchain_list(lc_doc_list)
def _initialize_by_component_configer(self,
doc_processor_configer: ComponentConfiger) -> 'DocProcessor':
"""Initialize splitter parameters from configuration.
Args:
doc_processor_configer: Configuration object containing splitter parameters.
Returns:
Initialized document processor instance.
"""
super()._initialize_by_component_configer(doc_processor_configer)
if hasattr(doc_processor_configer, "chunk_size"):
self.chunk_size = doc_processor_configer.chunk_size
if hasattr(doc_processor_configer, "chunk_overlap"):
self.chunk_overlap = doc_processor_configer.chunk_overlap
if hasattr(doc_processor_configer, "separators"):
self.separators = doc_processor_configer.separators
return self
@@ -0,0 +1,11 @@
name: 'recursive_character_text_splitter'
description: 'langchain recursive character text splitter'
chunk_size: 200
chunk_overlap: 20
separators:
- "\n\n"
- "\n"
metadata:
type: 'DOC_PROCESSOR'
module: 'agentuniverse.agent.action.knowledge.doc_processor.recursive_character_text_splitter'
class: 'RecursiveCharacterTextSplitter'
@@ -0,0 +1,335 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/12/04 00:00
# @Author : AI Assistant
# @Email : ai@example.com
# @FileName: semantic_deduplicator.py
import hashlib
import logging
from typing import List, Optional, Set, Dict, Tuple
from datetime import datetime
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import DocProcessor
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.agent.action.knowledge.embedding.embedding_manager import EmbeddingManager
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
logger = logging.getLogger(__name__)
class SemanticDeduplicator(DocProcessor):
"""Remove duplicate or near-duplicate documents using semantic similarity.
This processor identifies and removes duplicate documents using multiple strategies:
1. Exact match: Content hashing for identical documents
2. Semantic match: Embedding-based similarity for near-duplicates
3. Configurable merge strategies for handling duplicates
Attributes:
similarity_threshold: Similarity score threshold (0.0-1.0) for considering documents as duplicates.
exact_match_threshold: Threshold for exact matching (default 1.0).
merge_strategy: Strategy for handling duplicates ('keep_first', 'keep_best', 'merge').
use_embeddings: Whether to use embeddings for semantic similarity.
embedding_name: Name of the embedding model to use.
preserve_metadata: Whether to preserve metadata from deduplicated sources.
skip_on_error: Whether to skip documents that fail processing.
"""
similarity_threshold: float = 0.95
exact_match_threshold: float = 1.0
merge_strategy: str = 'keep_first' # 'keep_first', 'keep_best', 'merge'
use_embeddings: bool = True
embedding_name: Optional[str] = None
preserve_metadata: bool = True
skip_on_error: bool = True
def _process_docs(self, origin_docs: List[Document], query: Query = None) -> List[Document]:
"""Remove duplicate documents from the input list.
Args:
origin_docs: List of documents to deduplicate.
query: Optional query object (not used in this processor).
Returns:
List of deduplicated documents.
"""
if not origin_docs:
return []
logger.info(f"Starting deduplication of {len(origin_docs)} documents")
# Step 1: Exact duplicate removal using content hash
unique_docs, hash_map = self._remove_exact_duplicates(origin_docs)
logger.info(f"After exact match: {len(unique_docs)} unique documents")
# Step 2: Semantic duplicate removal using embeddings
if self.use_embeddings and len(unique_docs) > 1:
try:
unique_docs = self._remove_semantic_duplicates(unique_docs)
logger.info(f"After semantic match: {len(unique_docs)} unique documents")
except Exception as e:
logger.error(f"Semantic deduplication failed: {e}")
if not self.skip_on_error:
raise
# Step 3: Update metadata
for doc in unique_docs:
self._update_metadata(doc)
logger.info(f"Deduplication complete: {len(origin_docs)} -> {len(unique_docs)} documents")
return unique_docs
def _remove_exact_duplicates(self, docs: List[Document]) -> Tuple[List[Document], Dict[str, List[Document]]]:
"""Remove exact duplicates using content hashing.
Args:
docs: List of documents to process.
Returns:
Tuple of (unique documents, hash map of duplicates).
"""
hash_map: Dict[str, List[Document]] = {}
seen_hashes: Set[str] = set()
unique_docs: List[Document] = []
for doc in docs:
try:
content_hash = self._compute_hash(doc.text)
if content_hash not in hash_map:
hash_map[content_hash] = []
hash_map[content_hash].append(doc)
if content_hash not in seen_hashes:
seen_hashes.add(content_hash)
unique_docs.append(doc)
else:
# Handle duplicate based on merge strategy
if self.merge_strategy == 'keep_best':
# Replace if current doc is "better" (e.g., has more metadata)
existing_idx = next(i for i, d in enumerate(unique_docs)
if self._compute_hash(d.text) == content_hash)
if self._is_better_doc(doc, unique_docs[existing_idx]):
unique_docs[existing_idx] = doc
elif self.merge_strategy == 'merge':
# Merge metadata from duplicate
existing_idx = next(i for i, d in enumerate(unique_docs)
if self._compute_hash(d.text) == content_hash)
unique_docs[existing_idx] = self._merge_docs(unique_docs[existing_idx], doc)
except Exception as e:
logger.error(f"Failed to process document {doc.id}: {e}")
if not self.skip_on_error:
raise
# Keep the document if skip_on_error is True
unique_docs.append(doc)
return unique_docs, hash_map
def _remove_semantic_duplicates(self, docs: List[Document]) -> List[Document]:
"""Remove semantic duplicates using embeddings.
Args:
docs: List of documents to process.
Returns:
List of documents with semantic duplicates removed.
"""
if not self.embedding_name:
logger.warning("No embedding model specified, skipping semantic deduplication")
return docs
try:
# Get embedding model
embedding_manager = EmbeddingManager()
embedding_model = embedding_manager.get_instance_obj(self.embedding_name)
# Compute embeddings for all documents
texts = [doc.text for doc in docs]
embeddings = embedding_model.get_embeddings(texts)
# Update document embeddings
for doc, embedding in zip(docs, embeddings):
doc.embedding = embedding
# Find and remove semantic duplicates
unique_docs = []
seen_indices = set()
for i, doc in enumerate(docs):
if i in seen_indices:
continue
# Add document to unique set
unique_docs.append(doc)
seen_indices.add(i)
# Check for semantic duplicates
for j in range(i + 1, len(docs)):
if j in seen_indices:
continue
similarity = self._compute_similarity(embeddings[i], embeddings[j])
if similarity >= self.similarity_threshold:
seen_indices.add(j)
# Handle duplicate based on merge strategy
if self.merge_strategy == 'keep_best':
if self._is_better_doc(docs[j], doc):
# Replace with better document
unique_docs[-1] = docs[j]
elif self.merge_strategy == 'merge':
# Merge metadata
unique_docs[-1] = self._merge_docs(unique_docs[-1], docs[j])
return unique_docs
except Exception as e:
logger.error(f"Semantic deduplication error: {e}")
raise
def _compute_hash(self, text: str) -> str:
"""Compute SHA-256 hash of text content.
Args:
text: Text content to hash.
Returns:
Hex string of hash.
"""
return hashlib.sha256(text.encode('utf-8')).hexdigest()
def _compute_similarity(self, embedding1: List[float], embedding2: List[float]) -> float:
"""Compute cosine similarity between two embeddings.
Args:
embedding1: First embedding vector.
embedding2: Second embedding vector.
Returns:
Cosine similarity score (0.0-1.0).
"""
# Compute dot product
dot_product = sum(a * b for a, b in zip(embedding1, embedding2))
# Compute magnitudes
magnitude1 = sum(a * a for a in embedding1) ** 0.5
magnitude2 = sum(b * b for b in embedding2) ** 0.5
# Handle zero magnitude
if magnitude1 == 0 or magnitude2 == 0:
return 0.0
# Compute cosine similarity
return dot_product / (magnitude1 * magnitude2)
def _is_better_doc(self, doc1: Document, doc2: Document) -> bool:
"""Determine if doc1 is "better" than doc2.
Currently uses metadata richness as the criterion.
Args:
doc1: First document.
doc2: Second document.
Returns:
True if doc1 is better than doc2.
"""
metadata1 = doc1.metadata or {}
metadata2 = doc2.metadata or {}
# Compare metadata richness
score1 = len(metadata1) + len(doc1.keywords)
score2 = len(metadata2) + len(doc2.keywords)
return score1 > score2
def _merge_docs(self, doc1: Document, doc2: Document) -> Document:
"""Merge two documents, combining their metadata.
Args:
doc1: First document (base).
doc2: Second document to merge.
Returns:
Merged document.
"""
if not self.preserve_metadata:
return doc1
# Merge metadata
merged_metadata = doc1.metadata.copy() if doc1.metadata else {}
if doc2.metadata:
for key, value in doc2.metadata.items():
if key not in merged_metadata:
merged_metadata[key] = value
elif isinstance(value, list) and isinstance(merged_metadata[key], list):
# Merge lists
merged_metadata[key] = list(set(merged_metadata[key] + value))
# Merge keywords
merged_keywords = doc1.keywords.union(doc2.keywords)
# Track merged sources
if 'merged_sources' not in merged_metadata:
merged_metadata['merged_sources'] = []
merged_metadata['merged_sources'].append({
'id': doc2.id,
'merge_time': datetime.now().isoformat()
})
# Create merged document
merged_doc = Document(
id=doc1.id,
text=doc1.text,
metadata=merged_metadata,
embedding=doc1.embedding,
keywords=merged_keywords
)
return merged_doc
def _update_metadata(self, doc: Document) -> None:
"""Update document metadata with processing information.
Args:
doc: Document to update.
"""
if doc.metadata is None:
doc.metadata = {}
doc.metadata['processor_name'] = self.name
doc.metadata['processor_version'] = '1.0'
doc.metadata['processing_timestamp'] = datetime.now().isoformat()
doc.metadata['deduplication_strategy'] = self.merge_strategy
def _initialize_by_component_configer(self,
doc_processor_configer: ComponentConfiger) -> 'SemanticDeduplicator':
"""Initialize deduplicator parameters from configuration.
Args:
doc_processor_configer: Configuration object containing deduplicator parameters.
Returns:
Initialized document processor instance.
"""
super()._initialize_by_component_configer(doc_processor_configer)
if hasattr(doc_processor_configer, "similarity_threshold"):
self.similarity_threshold = doc_processor_configer.similarity_threshold
if hasattr(doc_processor_configer, "exact_match_threshold"):
self.exact_match_threshold = doc_processor_configer.exact_match_threshold
if hasattr(doc_processor_configer, "merge_strategy"):
self.merge_strategy = doc_processor_configer.merge_strategy
if hasattr(doc_processor_configer, "use_embeddings"):
self.use_embeddings = doc_processor_configer.use_embeddings
if hasattr(doc_processor_configer, "embedding_name"):
self.embedding_name = doc_processor_configer.embedding_name
if hasattr(doc_processor_configer, "preserve_metadata"):
self.preserve_metadata = doc_processor_configer.preserve_metadata
if hasattr(doc_processor_configer, "skip_on_error"):
self.skip_on_error = doc_processor_configer.skip_on_error
return self
@@ -0,0 +1,13 @@
name: 'semantic_deduplicator'
description: 'Remove semantic duplicates from documents using content hashing and embedding-based similarity'
similarity_threshold: 0.95
exact_match_threshold: 1.0
merge_strategy: 'keep_first' # Options: 'keep_first', 'keep_best', 'merge'
use_embeddings: true
embedding_name: 'default_embedding'
preserve_metadata: true
skip_on_error: true
metadata:
type: 'DOC_PROCESSOR'
module: 'agentuniverse.agent.action.knowledge.doc_processor.semantic_deduplicator'
class: 'SemanticDeduplicator'
@@ -0,0 +1,852 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/12/04 00:00
# @Author : AI Assistant
# @Email : ai@example.com
# @FileName: supply_chain_entity_extractor.py
import json
import logging
from typing import List, Optional, Dict, Any, Set
from dataclasses import dataclass, field
from datetime import datetime
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import DocProcessor
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.llm.llm_manager import LLMManager
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
logger = logging.getLogger(__name__)
@dataclass
class Entity:
"""Represents an entity in the supply chain.
Attributes:
name: Entity name.
entity_type: Type of entity (supplier, manufacturer, etc.).
attributes: Additional attributes.
confidence: Extraction confidence score.
"""
name: str
entity_type: str
attributes: Dict[str, Any] = field(default_factory=dict)
confidence: float = 1.0
@dataclass
class Relationship:
"""Represents a relationship between entities.
Attributes:
source: Source entity name.
target: Target entity name.
relationship_type: Type of relationship.
attributes: Additional attributes.
confidence: Extraction confidence score.
"""
source: str
target: str
relationship_type: str
attributes: Dict[str, Any] = field(default_factory=dict)
confidence: float = 1.0
class SupplyChainEntityExtractor(DocProcessor):
"""Extract supply chain entities and relationships from documents.
This processor uses both pattern matching and LLM-based extraction to identify:
1. Supply chain entities (suppliers, manufacturers, distributors, products)
2. Relationships between entities (supplies, manufactures, ships_to)
3. Knowledge graph structure for supply networks
Attributes:
entity_types: List of entity types to extract.
relationship_types: List of relationship types to extract.
use_llm: Whether to use LLM for entity extraction.
llm_name: Name of the LLM to use.
confidence_threshold: Minimum confidence for entity extraction.
extract_attributes: Whether to extract entity attributes.
skip_on_error: Whether to skip documents that fail processing.
"""
entity_types: List[str] = None
relationship_types: List[str] = None
use_llm: bool = True
llm_name: Optional[str] = None
confidence_threshold: float = 0.7
extract_attributes: bool = True
skip_on_error: bool = True
def __init__(self, **data):
super().__init__(**data)
if self.entity_types is None:
self.entity_types = [
'supplier',
'manufacturer',
'distributor',
'retailer',
'product',
'warehouse',
'logistics_provider',
'customer',
]
if self.relationship_types is None:
self.relationship_types = [
'supplies',
'manufactures',
'distributes',
'ships_to',
'stores',
'depends_on',
'partners_with',
]
def _process_docs(self, origin_docs: List[Document], query: Query = None) -> List[Document]:
"""Extract supply chain entities and relationships from documents.
Args:
origin_docs: List of supply chain documents.
query: Optional query object (not used in this processor).
Returns:
List of documents with extracted entities and relationships.
"""
if not origin_docs:
return []
logger.info(f"Starting supply chain entity extraction from {len(origin_docs)} documents")
processed_docs = []
for doc in origin_docs:
try:
enhanced_doc = self._extract_from_document(doc)
processed_docs.append(enhanced_doc)
logger.info(f"Extracted entities from document {doc.id}")
except Exception as e:
logger.error(f"Failed to extract from document {doc.id}: {e}")
if not self.skip_on_error:
raise
processed_docs.append(doc)
logger.info(f"Entity extraction complete for {len(processed_docs)} documents")
return processed_docs
def _extract_from_document(self, doc: Document) -> Document:
"""Extract entities and relationships from a single document.
Args:
doc: Supply chain document.
Returns:
Document with extracted entities and relationships in metadata.
"""
text = doc.text
# Step 1: Extract entities
entities = []
if self.use_llm and self.llm_name:
entities = self._extract_entities_with_llm(text)
else:
entities = self._extract_entities_with_patterns(text)
logger.debug(f"Extracted {len(entities)} entities")
# Step 2: Extract relationships
relationships = []
if len(entities) > 1:
if self.use_llm and self.llm_name:
relationships = self._extract_relationships_with_llm(text, entities)
else:
relationships = self._extract_relationships_with_patterns(text, entities)
logger.debug(f"Extracted {len(relationships)} relationships")
# Step 3: Build knowledge graph
graph = self._build_knowledge_graph(entities, relationships)
# Step 4: Create enhanced document
enhanced_doc = self._create_enhanced_document(doc, entities, relationships, graph)
return enhanced_doc
def _extract_entities_with_llm(self, text: str) -> List[Entity]:
"""Extract entities using LLM.
Args:
text: Document text.
Returns:
List of Entity objects.
"""
try:
llm_manager = LLMManager()
llm = llm_manager.get_instance_obj(self.llm_name)
# Construct prompt
prompt = self._build_entity_extraction_prompt(text)
# Call LLM
messages = [{"role": "user", "content": prompt}]
response = llm.call(messages=messages)
# Parse response
entities = self._parse_llm_entity_response(response)
# Filter by confidence
entities = [e for e in entities if e.confidence >= self.confidence_threshold]
return entities
except Exception as e:
logger.error(f"LLM entity extraction failed: {e}")
# Fallback to pattern-based extraction
return self._extract_entities_with_patterns(text)
def _build_entity_extraction_prompt(self, text: str) -> str:
"""Build prompt for LLM entity extraction.
Args:
text: Document text.
Returns:
Prompt string.
"""
entity_types_str = ', '.join(self.entity_types)
prompt = f"""Extract supply chain entities from the following text.
Entity types to extract: {entity_types_str}
For each entity, provide:
1. Entity name
2. Entity type
3. Confidence score (0.0-1.0)
Text:
{text[:2000]}
Return results in JSON format:
{{
"entities": [
{{"name": "Entity Name", "type": "entity_type", "confidence": 0.9}}
]
}}
"""
return prompt
def _parse_llm_entity_response(self, response: str) -> List[Entity]:
"""Parse LLM response for entities.
Args:
response: LLM response text.
Returns:
List of Entity objects.
"""
entities = []
try:
# Try to parse as JSON
data = json.loads(response)
entity_list = data.get('entities', [])
for item in entity_list:
entity = Entity(
name=item.get('name', ''),
entity_type=item.get('type', 'unknown'),
confidence=float(item.get('confidence', 0.5))
)
entities.append(entity)
except json.JSONDecodeError:
# Fallback: parse text format
logger.warning("Failed to parse JSON response, using text parsing")
entities = self._parse_text_entity_response(response)
return entities
def _parse_text_entity_response(self, response: str) -> List[Entity]:
"""Parse text format entity response.
Args:
response: Response text.
Returns:
List of Entity objects.
"""
entities = []
lines = response.split('\n')
for line in lines:
# Look for patterns like "- EntityName (type)"
if line.strip().startswith('-') or line.strip().startswith('*'):
# Simple parsing
parts = line.strip().lstrip('-*').strip().split('(')
if len(parts) >= 2:
name = parts[0].strip()
entity_type = parts[1].split(')')[0].strip()
entities.append(Entity(name=name, entity_type=entity_type, confidence=0.7))
return entities
def _extract_entities_with_patterns(self, text: str) -> List[Entity]:
"""Extract entities using pattern matching (fallback method).
Args:
text: Document text.
Returns:
List of Entity objects.
"""
entities = []
# Comprehensive pattern-based entity extraction for all 8 entity types
# Use strict patterns that match specific entity formats
# Separate case-sensitive patterns (company names) from case-insensitive (verbs)
case_sensitive_patterns = {
'supplier': [
# Company name patterns - capture full name INCLUDING suffix
r'\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Z][A-Za-z]{2,15}){0,2}\s+Supplier)\b', # "ABC Supplier"
r'\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Z][A-Za-z]{2,15}){0,2}\s+(?:Components|Materials))\b', # "ABC Components", "DEF Materials"
r'\b([A-Z][A-Za-z]+公司)\b', # "ABC公司"
],
'manufacturer': [
r'\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Z][A-Za-z]{2,15}){0,2}\s+(?:Manufacturing|Factory))\b', # "XYZ Manufacturing"
r'\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Z][A-Za-z]{2,15}){0,2}\s+Manufacturer)\b',
],
'distributor': [
r'\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Z][A-Za-z]{2,15}){0,2}\s+(?:Distributor|Distribution))\b',
],
'warehouse': [
r'\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Z][A-Za-z]{2,15}){0,2}\s+(?:Warehouse|Storage))\b',
r'\b([A-Z][A-Za-z\u4e00-\u9fa5]{2,15}\s*仓库)\b',
],
'retailer': [
r'\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Z][A-Za-z]{2,15}){0,2}\s+(?:Store|Retail|Shop|Market))\b',
],
'logistics_provider': [
r'\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Z][A-Za-z]{2,15}){0,2}\s+(?:Logistics|Shipping|Transport|Freight))\b',
],
'customer': [
r'\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Z][A-Za-z]{2,15}){0,2}\s+(?:Inc\.|Ltd\.|Corp\.|Co\.))\b',
],
}
case_insensitive_patterns = {
'supplier': [
r'supplier[s]?:\s*\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,3})\b',
r'supplied\s+by\s+\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,2})\b',
],
'manufacturer': [
r'manufactured\s+(?:by|at)\s+\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,2})\b',
r'produced\s+by\s+\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,2})\b',
],
'distributor': [
r'distributed\s+by\s+\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,2})\b',
r'regional\s+(distributors?)\b',
],
'warehouse': [
r'\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,3})\s+distribution\s+center\b',
],
'retailer': [
r'retailer[s]?:\s*\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,3})\b',
r'零售商:\s*\b([A-Z一-龥][A-Za-z一-龥]{2,15}(?:\s+[A-Za-z一-龥]{2,15}){0,2})\b',
r'sold\s+(?:by|at|through)\s+\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,2})\b',
r'retail\s+(?:through|at)\s+\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,2})\b',
],
'logistics_provider': [
r'logistics\s+provider[s]?:\s*\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,3})\b',
r'物流商:\s*\b([A-Z一-龥][A-Za-z一-龥]{2,15}(?:\s+[A-Za-z一-龥]{2,15}){0,2})\b',
r'shipped\s+by\s+\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,2})\b',
r'delivery\s+by\s+\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,2})\b',
r'transported\s+by\s+\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,2})\b',
],
'product': [
r'product[s]?:\s*\b([A-Z][A-Za-z0-9]{2,15}(?:\s+[A-Za-z0-9\-]{2,15}){0,3})\b',
r'产品:\s*\b([A-Z一-龥][A-Za-z一-龥0-9]{2,15}(?:\s+[A-Za-z一-龥0-9\-]{2,15}){0,2})\b',
r'(?:produces?|manufactures?)\s+\b([A-Z][A-Za-z0-9]{2,15}(?:\s+[A-Za-z0-9\-]{2,15}){0,3})\b',
r'item[s]?:\s*\b([A-Z][A-Za-z0-9]{2,15}(?:\s+[A-Za-z0-9\-]{2,15}){0,3})\b',
],
'customer': [
r'customer[s]?:\s*\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,3})\b',
r'客户:\s*\b([A-Z一-龥][A-Za-z一-龥]{2,15}(?:\s+[A-Za-z一-龥]{2,15}){0,2})\b',
r'sold\s+to\s+\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,2})\b',
r'delivered\s+to\s+\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,2})\b',
r'ordered\s+by\s+\b([A-Z][A-Za-z]{2,15}(?:\s+[A-Za-z]{2,15}){0,2})\b',
],
}
import re
# Process case-sensitive patterns (no re.IGNORECASE)
for entity_type, pattern_list in case_sensitive_patterns.items():
for pattern in pattern_list:
matches = re.finditer(pattern, text)
for match in matches:
name = match.group(1).strip()
if len(name) >= 3 and not name.lower() in ['the', 'and', 'for', 'from', 'with', 'are', 'was', 'not']:
name = name.rstrip('.,;:')
entities.append(Entity(
name=name,
entity_type=entity_type,
confidence=0.75 # Pattern-based extraction has moderate confidence
))
# Process case-insensitive patterns (with re.IGNORECASE)
for entity_type, pattern_list in case_insensitive_patterns.items():
for pattern in pattern_list:
matches = re.finditer(pattern, text, re.IGNORECASE)
for match in matches:
name = match.group(1).strip()
if len(name) >= 3 and not name.lower() in ['the', 'and', 'for', 'from', 'with', 'are', 'was', 'not', 'provides', 'supplies']:
name = name.rstrip('.,;:')
entities.append(Entity(
name=name,
entity_type=entity_type,
confidence=0.75
))
# Deduplicate by name (keep first occurrence with highest confidence)
seen = {}
for entity in entities:
if entity.name not in seen or entity.confidence > seen[entity.name].confidence:
seen[entity.name] = entity
unique_entities = list(seen.values())
# Extract attributes for entities if enabled
if self.extract_attributes:
for entity in unique_entities:
entity.attributes = self._extract_entity_attributes(entity.name, text)
return unique_entities
def _extract_entity_attributes(self, entity_name: str, text: str) -> Dict[str, Any]:
"""Extract attributes for an entity from the text.
Args:
entity_name: Name of the entity to extract attributes for.
text: Full document text.
Returns:
Dictionary of extracted attributes.
"""
attributes = {}
import re
# Escape entity name for regex
safe_name = re.escape(entity_name)
# Location extraction patterns
location_patterns = [
rf'{safe_name}.*?(?:located in|based in|in)\s+([A-Z][a-z]+(?:,\s*[A-Z][a-z]+)*)',
rf'(?:located in|based in|in)\s+([A-Z][a-z]+(?:,\s*[A-Z][a-z]+)*?).*?{safe_name}',
]
for pattern in location_patterns:
match = re.search(pattern, text, re.IGNORECASE)
if match:
attributes['location'] = match.group(1).strip()
break
# Founded year extraction
founded_pattern = rf'{safe_name}.*?founded\s+(\d{{4}})'
match = re.search(founded_pattern, text, re.IGNORECASE)
if match:
attributes['founded'] = match.group(1)
# Revenue extraction
revenue_patterns = [
rf'{safe_name}.*?revenue[:\s]+\$(\d+(?:\.\d+)?[MBK]?)',
rf'revenue[:\s]+\$(\d+(?:\.\d+)?[MBK]?).*?{safe_name}',
]
for pattern in revenue_patterns:
match = re.search(pattern, text, re.IGNORECASE)
if match:
attributes['revenue'] = f"${match.group(1)}"
break
return attributes
def _extract_relationships_with_llm(self, text: str, entities: List[Entity]) -> List[Relationship]:
"""Extract relationships using LLM.
Args:
text: Document text.
entities: Extracted entities.
Returns:
List of Relationship objects.
"""
try:
llm_manager = LLMManager()
llm = llm_manager.get_instance_obj(self.llm_name)
# Construct prompt
prompt = self._build_relationship_extraction_prompt(text, entities)
# Call LLM
messages = [{"role": "user", "content": prompt}]
response = llm.call(messages=messages)
# Parse response
relationships = self._parse_llm_relationship_response(response)
# Filter by confidence
relationships = [r for r in relationships if r.confidence >= self.confidence_threshold]
return relationships
except Exception as e:
logger.error(f"LLM relationship extraction failed: {e}")
return self._extract_relationships_with_patterns(text, entities)
def _build_relationship_extraction_prompt(self, text: str, entities: List[Entity]) -> str:
"""Build prompt for LLM relationship extraction.
Args:
text: Document text.
entities: Extracted entities.
Returns:
Prompt string.
"""
entity_names = [e.name for e in entities]
entity_names_str = ', '.join(entity_names)
relationship_types_str = ', '.join(self.relationship_types)
prompt = f"""Extract supply chain relationships between entities in the following text.
Entities: {entity_names_str}
Relationship types: {relationship_types_str}
For each relationship, provide:
1. Source entity
2. Target entity
3. Relationship type
4. Confidence score (0.0-1.0)
Text:
{text[:2000]}
Return results in JSON format:
{{
"relationships": [
{{"source": "Entity1", "target": "Entity2", "type": "supplies", "confidence": 0.9}}
]
}}
"""
return prompt
def _parse_llm_relationship_response(self, response: str) -> List[Relationship]:
"""Parse LLM response for relationships.
Args:
response: LLM response text.
Returns:
List of Relationship objects.
"""
relationships = []
try:
data = json.loads(response)
relationship_list = data.get('relationships', [])
for item in relationship_list:
relationship = Relationship(
source=item.get('source', ''),
target=item.get('target', ''),
relationship_type=item.get('type', 'related_to'),
confidence=float(item.get('confidence', 0.5))
)
relationships.append(relationship)
except json.JSONDecodeError:
logger.warning("Failed to parse JSON response for relationships")
return relationships
def _extract_relationships_with_patterns(self, text: str, entities: List[Entity]) -> List[Relationship]:
"""Extract relationships using pattern matching (fallback method).
Args:
text: Document text.
entities: Extracted entities.
Returns:
List of Relationship objects.
"""
relationships = []
entity_names = {e.name for e in entities}
entity_map = {e.name: e for e in entities}
import re
# Define relationship patterns with specific verbs
relationship_patterns = {
'supplies': [
r'{entity1}\s+supplies?\s+.{{0,50}}\s+(?:to\s+)?{entity2}', # Allow 0-50 chars between
r'{entity1}\s+supplied\s+.{{0,50}}\s+(?:to\s+)?{entity2}',
r'{entity2}\s+receives?\s+.{{0,30}}\s+(?:from\s+)?{entity1}',
r'{entity2}\s+(?:sources?|sourced)\s+.{{0,30}}\s+from\s+{entity1}',
r'{entity1}\s+provides?\s+.{{0,50}}\s+(?:to\s+)?{entity2}',
],
'manufactures': [
r'{entity1}\s+(?:manufactures?|produces?|makes?)\s+.{{0,30}}\s+{entity2}',
r'{entity2}\s+(?:manufactured|produced|made)\s+.{{0,20}}\s+(?:by\s+)?{entity1}',
r'{entity1}\s+production\s+of\s+{entity2}',
],
'distributes': [
r'{entity1}\s+distributes?\s+.{{0,30}}\s+(?:to\s+)?{entity2}',
r'{entity2}\s+receives?\s+distribution\s+from\s+{entity1}',
r'{entity1}\s+ships?\s+.{{0,30}}\s+(?:to\s+)?{entity2}',
],
'stores': [
r'{entity1}\s+stores?\s+{entity2}',
r'{entity2}\s+stored\s+(?:at|in)\s+{entity1}',
r'{entity1}\s+inventory\s+(?:of|includes)\s+{entity2}',
],
'ships_to': [
r'{entity1}\s+ships?\s+.{{0,30}}\s+(?:to\s+)?{entity2}',
r'{entity1}\s+delivers?\s+.{{0,30}}\s+(?:to\s+)?{entity2}',
r'{entity2}\s+receives?\s+(?:delivery|shipment)\s+from\s+{entity1}',
r'{entity1}\s+transports?\s+.{{0,30}}\s+(?:to\s+)?{entity2}',
r'shipped\s+to\s+(?:the\s+)?{entity2}', # "shipped to the Los Angeles distribution center"
],
'sells_to': [
r'{entity1}\s+sells?\s+.{{0,30}}\s+(?:to\s+)?{entity2}',
r'{entity2}\s+buys?\s+from\s+{entity1}',
r'{entity2}\s+purchases?\s+from\s+{entity1}',
],
'depends_on': [
r'{entity1}\s+depends?\s+on\s+{entity2}(?:\s+for\s+.{{0,30}})?', # "depends on ABC for components"
r'{entity1}\s+(?:is\s+)?dependent\s+on\s+{entity2}',
r'{entity1}\s+reliant\s+on\s+{entity2}',
r'{entity1}\s+relies\s+on\s+{entity2}',
],
}
# Try explicit relationship patterns first
for e1 in entities:
for e2 in entities:
if e1.name == e2.name:
continue
# Try each relationship pattern
for rel_type, patterns in relationship_patterns.items():
for pattern_template in patterns:
pattern = pattern_template.format(
entity1=re.escape(e1.name),
entity2=re.escape(e2.name)
)
if re.search(pattern, text, re.IGNORECASE):
relationships.append(Relationship(
source=e1.name,
target=e2.name,
relationship_type=rel_type,
confidence=0.85 # High confidence for explicit patterns
))
break # Found explicit relationship, no need to check other patterns
# Fallback: entities mentioned close together with inferred relationship
found_pairs = {(r.source, r.target) for r in relationships}
for e1 in entities:
for e2 in entities:
if e1.name == e2.name or (e1.name, e2.name) in found_pairs:
continue
# Check if both entities appear in same sentence (proximity heuristic)
pattern = f"{re.escape(e1.name)}.{{0,150}}{re.escape(e2.name)}"
if re.search(pattern, text, re.IGNORECASE):
# Infer relationship type based on entity types
rel_type = self._infer_relationship_type(e1.entity_type, e2.entity_type)
relationships.append(Relationship(
source=e1.name,
target=e2.name,
relationship_type=rel_type,
confidence=0.60 # Lower confidence for inferred relationships
))
# Deduplicate relationships
seen = set()
unique_relationships = []
for rel in relationships:
key = (rel.source, rel.target, rel.relationship_type)
if key not in seen:
seen.add(key)
unique_relationships.append(rel)
return unique_relationships
def _infer_relationship_type(self, source_type: str, target_type: str) -> str:
"""Infer relationship type based on entity types.
Args:
source_type: Source entity type.
target_type: Target entity type.
Returns:
Relationship type.
"""
# Simple heuristics
if source_type == 'supplier' and target_type == 'manufacturer':
return 'supplies'
elif source_type == 'manufacturer' and target_type == 'product':
return 'manufactures'
elif source_type == 'distributor' and target_type in ['retailer', 'customer']:
return 'ships_to'
else:
return 'related_to'
def _build_knowledge_graph(self, entities: List[Entity],
relationships: List[Relationship]) -> Dict[str, Any]:
"""Build knowledge graph from entities and relationships.
Args:
entities: List of entities.
relationships: List of relationships.
Returns:
Knowledge graph as dictionary.
"""
graph = {
'nodes': [],
'edges': [],
'stats': {
'node_count': len(entities),
'edge_count': len(relationships),
}
}
# Add nodes
for entity in entities:
graph['nodes'].append({
'id': entity.name,
'type': entity.entity_type,
'confidence': entity.confidence,
'attributes': entity.attributes,
})
# Add edges
for rel in relationships:
graph['edges'].append({
'source': rel.source,
'target': rel.target,
'type': rel.relationship_type,
'confidence': rel.confidence,
'attributes': rel.attributes,
})
return graph
def _create_enhanced_document(self, original_doc: Document,
entities: List[Entity],
relationships: List[Relationship],
graph: Dict[str, Any]) -> Document:
"""Create enhanced document with entity and relationship metadata.
Args:
original_doc: Original document.
entities: Extracted entities.
relationships: Extracted relationships.
graph: Knowledge graph.
Returns:
Enhanced document.
"""
metadata = original_doc.metadata.copy() if original_doc.metadata else {}
# Save original metadata
original_metadata_backup = original_doc.metadata.copy() if original_doc.metadata else {}
metadata.update({
'processor_name': self.name,
'processor_version': '1.0',
'processing_timestamp': datetime.now().isoformat(),
'source_document_id': original_doc.id,
'original_metadata': original_metadata_backup,
})
# Add entities
entity_list = []
for entity in entities:
entity_list.append({
'name': entity.name,
'type': entity.entity_type,
'confidence': entity.confidence,
'attributes': entity.attributes,
})
metadata['entities'] = entity_list
metadata['entity_count'] = len(entities)
# Add relationships
relationship_list = []
for rel in relationships:
relationship_list.append({
'source': rel.source,
'target': rel.target,
'type': rel.relationship_type,
'confidence': rel.confidence,
})
metadata['relationships'] = relationship_list
metadata['relationship_count'] = len(relationships)
# Add knowledge graph
metadata['knowledge_graph'] = graph
# Add keywords
keywords = original_doc.keywords.copy() if original_doc.keywords else set()
for entity in entities:
keywords.add(entity.name)
keywords.add(entity.entity_type)
keywords.add('supply_chain')
# Create enhanced document
enhanced_doc = Document(
id=original_doc.id,
text=original_doc.text,
metadata=metadata,
embedding=original_doc.embedding,
keywords=keywords
)
return enhanced_doc
def _initialize_by_component_configer(self,
doc_processor_configer: ComponentConfiger) -> 'SupplyChainEntityExtractor':
"""Initialize extractor parameters from configuration.
Args:
doc_processor_configer: Configuration object.
Returns:
Initialized document processor instance.
"""
super()._initialize_by_component_configer(doc_processor_configer)
if hasattr(doc_processor_configer, "entity_types"):
self.entity_types = doc_processor_configer.entity_types
if hasattr(doc_processor_configer, "relationship_types"):
self.relationship_types = doc_processor_configer.relationship_types
if hasattr(doc_processor_configer, "use_llm"):
self.use_llm = doc_processor_configer.use_llm
if hasattr(doc_processor_configer, "llm_name"):
self.llm_name = doc_processor_configer.llm_name
if hasattr(doc_processor_configer, "confidence_threshold"):
self.confidence_threshold = doc_processor_configer.confidence_threshold
if hasattr(doc_processor_configer, "extract_attributes"):
self.extract_attributes = doc_processor_configer.extract_attributes
if hasattr(doc_processor_configer, "skip_on_error"):
self.skip_on_error = doc_processor_configer.skip_on_error
return self
@@ -0,0 +1,28 @@
name: 'supply_chain_entity_extractor'
description: 'Extract supply chain entities and relationships to build knowledge graphs'
use_llm: true
llm_name: 'default_llm'
confidence_threshold: 0.7
extract_attributes: true
skip_on_error: true
entity_types:
- supplier
- manufacturer
- distributor
- retailer
- product
- warehouse
- logistics_provider
- customer
relationship_types:
- supplies
- manufactures
- distributes
- ships_to
- stores
- depends_on
- partners_with
metadata:
type: 'DOC_PROCESSOR'
module: 'agentuniverse.agent.action.knowledge.doc_processor.supply_chain_entity_extractor'
class: 'SupplyChainEntityExtractor'
@@ -0,0 +1,333 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2025/12/09
# @Author : kaichuan
# @FileName: threshold_filter.py
import math
from typing import List, Dict, Any, Optional, Literal
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import DocProcessor
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
class ThresholdFilter(DocProcessor):
"""Multi-mode document filter supporting score, length, top-k, and percentile filtering.
This processor provides flexible document filtering capabilities with support for:
- Score threshold filtering (min/max relevance scores)
- Document length filtering (min/max text length)
- Top-K filtering (keep top K documents by score)
- Percentile filtering (keep top X% documents by score)
- AND/OR logic combination for multiple filters
Attributes:
filters: List of filter configurations, each specifying a filter type and parameters.
logic_operator: Logic operator for combining multiple filters ('AND' or 'OR').
score_field: Metadata field name containing relevance scores.
default_score: Default score for documents without score metadata.
preserve_order: Whether to maintain original document order in results.
Example:
```yaml
filters:
- type: 'score'
min_score: 0.7
- type: 'length'
min_length: 100
logic_operator: 'AND'
```
"""
filters: List[Dict[str, Any]] = []
logic_operator: Literal["AND", "OR"] = "AND"
score_field: str = "relevance_score"
default_score: float = 0.0
preserve_order: bool = True
# Filter type to handler method mapping
_FILTER_HANDLERS = {
"score": "_apply_score_filter",
"length": "_apply_length_filter",
"topk": "_apply_topk_filter",
"percentile": "_apply_percentile_filter"
}
def _process_docs(self, origin_docs: List[Document], query: Query = None) -> List[Document]:
"""Apply configured filters to documents.
Processing pipeline:
1. Validate input (return [] if empty, return all if no filters)
2. Apply each filter independently to create result sets
3. Combine result sets using logic operator
4. Optionally restore original order
5. Return filtered documents
Args:
origin_docs: List of documents to be filtered.
query: Query object (currently unused, but required by interface).
Returns:
List[Document]: Filtered documents based on configured criteria.
"""
# Handle empty input
if not origin_docs:
return []
# Handle no filters configured - pass through all documents
if not self.filters:
return origin_docs
# Apply each filter independently
filter_results = []
for filter_config in self.filters:
filter_type = filter_config.get("type")
if filter_type not in self._FILTER_HANDLERS:
raise ValueError(f"Invalid filter type: {filter_type}")
handler_name = self._FILTER_HANDLERS[filter_type]
handler = getattr(self, handler_name)
filtered = handler(origin_docs, filter_config)
filter_results.append(filtered)
# Combine results using logic operator
combined = self._combine_results(filter_results, self.logic_operator)
# Preserve original order if configured
if self.preserve_order:
combined = self._restore_order(combined, origin_docs)
return combined
def _apply_score_filter(self, docs: List[Document], config: Dict[str, Any]) -> List[Document]:
"""Filter documents by score range.
Filters documents based on min_score and/or max_score thresholds.
Documents without scores use default_score.
Args:
docs: Documents to filter.
config: Filter configuration with 'min_score' and/or 'max_score'.
Returns:
List[Document]: Documents within the specified score range.
"""
min_score = config.get("min_score", float("-inf"))
max_score = config.get("max_score", float("inf"))
filtered = []
for doc in docs:
score = self._get_score(doc)
if min_score <= score <= max_score:
filtered.append(doc)
return filtered
def _apply_length_filter(self, docs: List[Document], config: Dict[str, Any]) -> List[Document]:
"""Filter documents by text length.
Filters documents based on min_length and/or max_length thresholds.
Documents with None or empty text are treated as length 0.
Args:
docs: Documents to filter.
config: Filter configuration with 'min_length' and/or 'max_length'.
Returns:
List[Document]: Documents within the specified length range.
"""
min_length = config.get("min_length", 0)
max_length = config.get("max_length", float("inf"))
filtered = []
for doc in docs:
length = len(doc.text) if doc.text else 0
if min_length <= length <= max_length:
filtered.append(doc)
return filtered
def _apply_topk_filter(self, docs: List[Document], config: Dict[str, Any]) -> List[Document]:
"""Keep top K documents by score.
Sorts documents by score in descending order and returns top K.
If k > len(docs), returns all documents.
Args:
docs: Documents to filter.
config: Filter configuration with 'k' parameter.
Returns:
List[Document]: Top K documents by score.
"""
k = config.get("k", len(docs))
# Score each document
scored_docs = [(doc, self._get_score(doc)) for doc in docs]
# Sort by score descending
scored_docs.sort(key=lambda x: x[1], reverse=True)
# Return top K
return [doc for doc, score in scored_docs[:k]]
def _apply_percentile_filter(self, docs: List[Document], config: Dict[str, Any]) -> List[Document]:
"""Keep top X% documents by score.
Calculates cutoff count as ceil(len(docs) * percentile), sorts by score,
and returns top documents. Percentile is clamped to [0.0, 1.0].
Args:
docs: Documents to filter.
config: Filter configuration with 'percentile' parameter (0.0-1.0).
Returns:
List[Document]: Top percentile documents by score.
"""
percentile = config.get("percentile", 1.0)
# Clamp percentile to valid range [0.0, 1.0]
percentile = max(0.0, min(1.0, percentile))
cutoff_count = math.ceil(len(docs) * percentile)
# Score each document
scored_docs = [(doc, self._get_score(doc)) for doc in docs]
# Sort by score descending
scored_docs.sort(key=lambda x: x[1], reverse=True)
# Return top percentile
return [doc for doc, score in scored_docs[:cutoff_count]]
def _get_score(self, doc: Document) -> float:
"""Extract score from document metadata.
Attempts to retrieve score from metadata[score_field].
Returns default_score if metadata is missing or score field not found.
Args:
doc: Document to extract score from.
Returns:
float: Document score or default_score if not found.
"""
if not doc.metadata:
return self.default_score
return doc.metadata.get(self.score_field, self.default_score)
def _combine_results(self, results: List[List[Document]], logic: str) -> List[Document]:
"""Combine filter results using AND/OR logic.
AND logic: Returns intersection - documents present in ALL result sets.
OR logic: Returns union - documents present in ANY result set.
Args:
results: List of filtered document lists from each filter.
logic: Logic operator ('AND' or 'OR').
Returns:
List[Document]: Combined result set based on logic operator.
"""
if not results:
return []
if len(results) == 1:
return results[0]
if logic == "AND":
# Intersection: documents present in ALL result sets
# Use document ID for comparison
result_set = set(id(doc) for doc in results[0])
for result in results[1:]:
result_set &= set(id(doc) for doc in result)
# Reconstruct documents preserving metadata
# Build map from all results to ensure we get the document objects
doc_map = {id(doc): doc for result in results for doc in result}
return [doc_map[doc_id] for doc_id in result_set if doc_id in doc_map]
else: # OR
# Union: documents present in ANY result set
seen = set()
combined = []
for result in results:
for doc in result:
doc_id = id(doc)
if doc_id not in seen:
seen.add(doc_id)
combined.append(doc)
return combined
def _restore_order(self, filtered_docs: List[Document], original_docs: List[Document]) -> List[Document]:
"""Restore original document order.
Iterates through original documents in order and includes those
present in the filtered set.
Args:
filtered_docs: Documents after filtering.
original_docs: Original document list with desired order.
Returns:
List[Document]: Filtered documents in original order.
"""
filtered_ids = set(id(doc) for doc in filtered_docs)
return [doc for doc in original_docs if id(doc) in filtered_ids]
def _initialize_by_component_configer(self, doc_processor_configer: ComponentConfiger) -> 'ThresholdFilter':
"""Initialize filter parameters from component configuration.
Validates configuration including filter types and logic operator.
Args:
doc_processor_configer: Configuration object containing filter parameters.
Returns:
ThresholdFilter: The initialized filter instance.
Raises:
ValueError: If configuration is invalid (bad filter type or logic operator).
"""
super()._initialize_by_component_configer(doc_processor_configer)
# Initialize filters
if hasattr(doc_processor_configer, "filters"):
self.filters = doc_processor_configer.filters
# Validate filter types
if not isinstance(self.filters, list):
raise ValueError("filters must be a list")
valid_types = {"score", "length", "topk", "percentile"}
for i, filter_config in enumerate(self.filters):
filter_type = filter_config.get("type")
if filter_type not in valid_types:
raise ValueError(f"Invalid filter type at index {i}: {filter_type}. "
f"Valid types are: {', '.join(valid_types)}")
# Initialize logic operator
if hasattr(doc_processor_configer, "logic_operator"):
self.logic_operator = doc_processor_configer.logic_operator
# Validate logic operator
if self.logic_operator not in {"AND", "OR"}:
raise ValueError(f"Invalid logic_operator: {self.logic_operator}. "
f"Must be 'AND' or 'OR'")
# Initialize score field
if hasattr(doc_processor_configer, "score_field"):
self.score_field = doc_processor_configer.score_field
# Initialize default score
if hasattr(doc_processor_configer, "default_score"):
self.default_score = doc_processor_configer.default_score
# Initialize preserve order
if hasattr(doc_processor_configer, "preserve_order"):
self.preserve_order = doc_processor_configer.preserve_order
return self
@@ -0,0 +1,39 @@
name: 'threshold_filter'
description: 'Multi-mode document filter with logic combination support for score, length, top-k, and percentile filtering'
metadata:
type: 'DOC_PROCESSOR'
module: 'agentuniverse.agent.action.knowledge.doc_processor.threshold_filter'
class: 'ThresholdFilter'
# Filter configuration - apply multiple filters with AND/OR logic
filters:
# Score threshold filter - filter by relevance score range
- type: 'score'
min_score: 0.5
# max_score: 1.0 # optional: maximum score threshold
# Document length filter - filter by text length range
- type: 'length'
min_length: 50
# max_length: 5000 # optional: maximum length threshold
# Top-K filter - keep top K documents by score
# - type: 'topk'
# k: 10
# Percentile filter - keep top X% documents by score
# - type: 'percentile'
# percentile: 0.8 # 0.0 to 1.0, keeps top 80%
# Logic operator for combining multiple filters
# AND: documents must pass ALL filters (intersection)
# OR: documents must pass ANY filter (union)
logic_operator: 'AND'
# Score extraction configuration
score_field: 'relevance_score' # metadata field containing scores
default_score: 0.0 # default score for documents without scores
# Output configuration
preserve_order: true # maintain original document order in results
@@ -0,0 +1,73 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/8/5 15:37
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: token_text_splitter.py
from typing import List, Optional
from langchain.text_splitter import TokenTextSplitter as Splitter
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import \
DocProcessor
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.config.component_configer.component_configer import \
ComponentConfiger
class TokenTextSplitter(DocProcessor):
"""Splits text into chunks based on token count rather than characters."""
chunk_size: int = 200
chunk_overlap: int = 20
encoding_name: str = 'gpt2'
model_name: Optional[str] = None
__splitter: Optional[Splitter] = None
@property
def splitter(self) -> Splitter:
if not self.__splitter:
self.__splitter = Splitter(
encoding_name=self.encoding_name,
model_name=self.model_name,
chunk_size=self.chunk_size,
chunk_overlap=self.chunk_overlap
)
return self.__splitter
def _process_docs(self, origin_docs: List[Document], query: Query = None) -> \
List[Document]:
"""Split documents based on token count using the specified tokenizer.
Args:
origin_docs: List of documents to be split.
query: Optional query object (not used in this processor).
Returns:
List of split document chunks.
"""
lc_doc_list = self.splitter.split_documents(Document.as_langchain_list(
origin_docs
))
return Document.from_langchain_list(lc_doc_list)
def _initialize_by_component_configer(self,
doc_processor_configer: ComponentConfiger) -> 'DocProcessor':
"""Initialize splitter parameters from configuration.
Args:
doc_processor_configer: Configuration object containing splitter parameters.
Returns:
Initialized document processor instance.
"""
super()._initialize_by_component_configer(doc_processor_configer)
if hasattr(doc_processor_configer, "chunk_size"):
self.chunk_size = doc_processor_configer.chunk_size
if hasattr(doc_processor_configer, "chunk_overlap"):
self.chunk_overlap = doc_processor_configer.chunk_overlap
if hasattr(doc_processor_configer, "encoding_name"):
self.encoding_name = doc_processor_configer.encoding_name
if hasattr(doc_processor_configer, "model_name"):
self.model_name = doc_processor_configer.model_name
return self
@@ -0,0 +1,8 @@
name: 'token_text_splitter'
description: 'langchain token text splitter'
chunk_size: 200
chunk_overlap: 20
metadata:
type: 'DOC_PROCESSOR'
module: 'agentuniverse.agent.action.knowledge.doc_processor.token_text_splitter'
class: 'TokenTextSplitter'
@@ -0,0 +1,11 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2025/3/4 15:05
# @Author : hiro
# @Email : hiromesh@qq.com
# @FileName: __init__.py
from agentuniverse.agent.action.knowledge.doc_processor.types.ast_types import *
from agentuniverse.agent.action.knowledge.doc_processor.types.code_types import *
from agentuniverse.agent.action.knowledge.doc_processor.types.metrics_types import *
@@ -0,0 +1,32 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2025/3/4 15:05
# @Author : hiro
# @Email : hiromesh@qq.com
# @FileName: ast_types.py
from typing import List, Any, Optional, TypedDict
class AstNodePoint(TypedDict):
row: int
column: int
class AstNode(TypedDict):
type: str
start_point: AstNodePoint
end_point: AstNodePoint
start_byte: int
end_byte: int
text: Optional[str]
children: Optional[List['AstNode']]
class CodeBoundary(TypedDict):
start: int
end: int
type: str
name: Optional[str]
node: Any
@@ -0,0 +1,36 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2025/3/4 15:06
# @Author : hiro
# @Email : hiromesh@qq.com
# @FileName: code_types.py
from typing import Dict, Optional, TypedDict
from agentuniverse.agent.action.knowledge.doc_processor.types.ast_types import AstNode
from agentuniverse.agent.action.knowledge.doc_processor.types.metrics_types import CodeMetrics
class CodeFeatures(TypedDict):
node_counts: Dict[str, int]
code_metrics: CodeMetrics
identifier_count: int
function_count: int
class_count: int
statement_count: int
class CodeRepresentation(TypedDict):
ast: AstNode
features: CodeFeatures
language: str
code_length: int
class ChunkRepresentation(TypedDict):
ast: AstNode
code: str
language: str
name: Optional[str]
type: str
@@ -0,0 +1,17 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2025/3/4 15:06
# @Author : hiro
# @Email : hiromesh@qq.com
# @FileName: metrics_types.py
from typing import TypedDict
class CodeMetrics(TypedDict):
line_count: int
code_line_count: int
avg_line_length: float
max_line_length: int
character_count: int
@@ -0,0 +1,7 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/4/2 17:07
# @Author : wangchongshi
# @Email : wangchongshi.wcs@antgroup.com
# @FileName: __init__.py
@@ -0,0 +1,237 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2025/12/10 14:30
# @Author : kaichuan
# @FileName: aws_bedrock_embedding.py
import json
from typing import Any, Optional, List
from pydantic import Field
from agentuniverse.base.util.env_util import get_from_env
from agentuniverse.agent.action.knowledge.embedding.embedding import Embedding
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
class AWSBedrockEmbedding(Embedding):
"""The AWS Bedrock embedding class.
Supports Amazon Titan and Cohere embedding models through AWS Bedrock Runtime.
Supported Models:
- amazon.titan-embed-text-v1 (1536 dimensions, fixed)
- amazon.titan-embed-text-v2 (configurable: 256, 384, 1024 dimensions)
- cohere.embed-english-v3 (1024 dimensions)
- cohere.embed-multilingual-v3 (1024 dimensions)
Environment Variables:
- AWS_ACCESS_KEY_ID: AWS access key ID
- AWS_SECRET_ACCESS_KEY: AWS secret access key
- AWS_REGION: AWS region (default: us-east-1)
"""
# AWS Configuration
aws_access_key_id: Optional[str] = Field(
default_factory=lambda: get_from_env("AWS_ACCESS_KEY_ID"))
aws_secret_access_key: Optional[str] = Field(
default_factory=lambda: get_from_env("AWS_SECRET_ACCESS_KEY"))
aws_region: Optional[str] = Field(
default_factory=lambda: get_from_env("AWS_REGION") or "us-east-1")
# Model Configuration
model_id: str = "amazon.titan-embed-text-v1"
normalize: bool = True
dimensions: Optional[int] = None # For titan-embed-text-v2
# Client
client: Any = None
def get_embeddings(self, texts: List[str], **kwargs) -> List[List[float]]:
"""Get embeddings from AWS Bedrock.
Args:
texts (List[str]): A list of texts to be embedded.
**kwargs: Additional arguments for model-specific parameters.
Returns:
List[List[float]]: A list of embeddings corresponding to the input texts.
Raises:
ValueError: If required configuration is missing or model is not supported.
Exception: If the API call fails.
"""
self._initialize_client()
if self.embedding_model_name is None:
raise ValueError("Must provide `embedding_model_name` (model_id)")
# Use embedding_model_name as model_id if provided
model_id = self.embedding_model_name or self.model_id
embeddings = []
for text in texts:
try:
# Prepare request body based on model type
if "titan" in model_id.lower():
body = {"inputText": text}
if self.normalize:
body["normalize"] = True
# Only add dimensions for titan-embed-text-v2
if "v2" in model_id and self.dimensions is not None:
body["dimensions"] = self.dimensions
elif "cohere" in model_id.lower():
body = {
"texts": [text],
"input_type": kwargs.get("input_type", "search_document")
}
else:
raise ValueError(f"Unsupported model: {model_id}")
# Invoke the model
response = self.client.invoke_model(
modelId=model_id,
body=json.dumps(body),
contentType="application/json",
accept="application/json"
)
# Parse response
response_body = json.loads(response['body'].read())
# Extract embedding based on model type
if "titan" in model_id.lower():
embedding = response_body.get('embedding')
elif "cohere" in model_id.lower():
embedding = response_body.get('embeddings', [None])[0]
else:
embedding = None
if embedding is None:
raise ValueError(f"Failed to extract embedding from response for model {model_id}")
embeddings.append(embedding)
except Exception as e:
raise Exception(f"Failed to get embedding for text: {str(e)}")
return embeddings
async def async_get_embeddings(self, texts: List[str], **kwargs) -> List[List[float]]:
"""Asynchronously get embeddings from AWS Bedrock.
Note: Currently delegates to synchronous implementation.
Future versions may use aioboto3 for true async support.
Args:
texts (List[str]): A list of texts to be embedded.
**kwargs: Additional arguments for model-specific parameters.
Returns:
List[List[float]]: A list of embeddings corresponding to the input texts.
Raises:
ValueError: If required configuration is missing or model is not supported.
Exception: If the API call fails.
"""
# For now, delegate to sync implementation
# Future: Use aioboto3 for true async support
return self.get_embeddings(texts, **kwargs)
def as_langchain(self) -> Any:
"""Convert to LangChain-compatible BedrockEmbeddings instance.
Returns:
BedrockEmbeddings: A LangChain BedrockEmbeddings instance.
"""
self._initialize_client()
from langchain_community.embeddings import BedrockEmbeddings
# Use embedding_model_name as model_id if provided
model_id = self.embedding_model_name or self.model_id
return BedrockEmbeddings(
client=self.client,
model_id=model_id,
region_name=self.aws_region
)
def _initialize_by_component_configer(self,
embedding_configer: ComponentConfiger) -> 'Embedding':
"""Initialize the embedding by the ComponentConfiger object.
Args:
embedding_configer(ComponentConfiger): A configer contains embedding configuration.
Returns:
Embedding: An AWSBedrockEmbedding instance.
"""
super()._initialize_by_component_configer(embedding_configer)
# Load AWS-specific configuration
if hasattr(embedding_configer, "aws_access_key_id"):
self.aws_access_key_id = embedding_configer.aws_access_key_id
if hasattr(embedding_configer, "aws_secret_access_key"):
self.aws_secret_access_key = embedding_configer.aws_secret_access_key
if hasattr(embedding_configer, "aws_region"):
self.aws_region = embedding_configer.aws_region
# Load model configuration
if hasattr(embedding_configer, "model_id"):
self.model_id = embedding_configer.model_id
if hasattr(embedding_configer, "normalize"):
self.normalize = embedding_configer.normalize
if hasattr(embedding_configer, "dimensions"):
self.dimensions = embedding_configer.dimensions
return self
def _initialize_client(self) -> None:
"""Initialize the AWS Bedrock Runtime client.
Raises:
ValueError: If required AWS credentials are missing.
"""
if self.client is not None:
return
# Validate required configuration
if not self.aws_region:
raise ValueError("AWS_REGION is missing. Please set the AWS_REGION environment variable.")
try:
import boto3
from botocore.config import Config
except ImportError:
raise ImportError(
"boto3 is required for AWS Bedrock embeddings. "
"Install it with: pip install boto3"
)
# Create boto3 session with credentials if provided
# If not provided, boto3 will use default credential chain (env vars, IAM roles, etc.)
session_kwargs = {}
if self.aws_access_key_id:
session_kwargs['aws_access_key_id'] = self.aws_access_key_id
if self.aws_secret_access_key:
session_kwargs['aws_secret_access_key'] = self.aws_secret_access_key
if self.aws_region:
session_kwargs['region_name'] = self.aws_region
session = boto3.Session(**session_kwargs)
# Create Bedrock Runtime client with retry configuration
self.client = session.client(
service_name='bedrock-runtime',
config=Config(
retries={
'max_attempts': 3,
'mode': 'adaptive'
}
)
)
@@ -0,0 +1,20 @@
name: 'aws_bedrock_embedding'
description: 'AWS Bedrock embedding supporting Amazon Titan and Cohere models'
embedding_model_name: 'amazon.titan-embed-text-v1'
embedding_dims: 1536
# AWS Configuration (read from environment variables by default)
# AWS_ACCESS_KEY_ID, AWS_SECRET_ACCESS_KEY, AWS_REGION
aws_region: 'us-east-1'
# Model-specific configuration
model_id: 'amazon.titan-embed-text-v1'
normalize: true
# Optional: For Titan v2, specify dimensions (256, 384, or 1024)
# dimensions: 1024
metadata:
type: 'EMBEDDING'
module: 'agentuniverse.agent.action.knowledge.embedding.aws_bedrock_embedding'
class: 'AWSBedrockEmbedding'
@@ -0,0 +1,143 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# @Time : 2/16/25 9:50 PM
# @Author : Xinyuan Xu
# @Email : xuxinyuan2019@gmail.com
# @FileName: azureopenai_embedding.py
from typing import Any, Optional, List
from pydantic import Field
from openai import AzureOpenAI, AsyncAzureOpenAI
from agentuniverse.base.util.env_util import get_from_env
from agentuniverse.agent.action.knowledge.embedding.embedding import Embedding
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
class AzureOpenAIEmbedding(Embedding):
"""The Azure OpenAI embedding class."""
azure_api_key: Optional[str] = Field(
default_factory=lambda: get_from_env("AZURE_OPENAI_API_KEY"))
resource_name: Optional[str] = Field(
default_factory=lambda: get_from_env("AZURE_OPENAI_RESOURCE_NAME"))
azure_api_version: Optional[str] = Field(
default_factory=lambda: get_from_env("AZURE_API_VERSION"))
embedding_model_name: Optional[str] = None
embedding_dims: Optional[int] = None
client: Any = None
async_client: Any = None
def get_embeddings(self, texts: List[str], **kwargs) -> List[List[float]]:
"""
Retrieve text embeddings for a list of input texts using Azure OpenAI API.
Args:
texts (List[str]): A list of input texts to be embedded.
Returns:
List[List[float]]: A list of embeddings corresponding to the input texts.
Raises:
Exception: If the API call fails or if required configuration is missing.
"""
self._initialize_clients()
try:
if self.embedding_dims is not None:
response = self.client.embeddings.create(
input=texts,
model=self.embedding_model_name,
dimensions=self.embedding_dims
)
else:
response = self.client.embeddings.create(
input=texts,
model=self.embedding_model_name
)
return [item.embedding for item in response.data]
except Exception as e:
raise Exception(f"Failed to get embeddings: {e}")
async def async_get_embeddings(self, texts: List[str], **kwargs) -> List[List[float]]:
"""
Retrieve text embeddings for a list of input texts using Azure OpenAI API asynchronously.
Args:
texts (List[str]): A list of input texts to be embedded.
Returns:
List[List[float]]: A list of embeddings corresponding to the input texts.
Raises:
Exception: If the API call fails or if required configuration is missing.
"""
self._initialize_clients()
try:
if self.embedding_dims is not None:
response = await self.async_client.embeddings.create(
input=texts,
model=self.embedding_model_name,
dimensions=self.embedding_dims
)
else:
response = await self.async_client.embeddings.create(
input=texts,
model=self.embedding_model_name
)
return [item.embedding for item in response.data]
except Exception as e:
raise Exception(f"Failed to get embeddings: {e}")
def as_langchain(self) -> Any:
"""
Convert the AzureOpenAIEmbedding instance to a LangChainAzureOpenAIEmbedding instance.
"""
self._initialize_clients()
from langchain_community.embeddings.azure_openai import AzureOpenAIEmbeddings
return AzureOpenAIEmbeddings(openai_api_key=self.azure_api_key, client=self.client.embeddings, async_client=self.async_client.embeddings, azure_endpoint=f"https://{self.resource_name}.openai.azure.com/")
def _initialize_by_component_configer(self, embedding_configer: ComponentConfiger) -> 'Embedding':
"""
Initialize the embedding by the ComponentConfiger object.
Args:
embedding_configer(ComponentConfiger): A configer contains embedding configuration.
Returns:
Embedding: A AzureOpenAIEmbedding instance.
"""
super()._initialize_by_component_configer(embedding_configer)
if hasattr(embedding_configer, "azure_api_key"):
self.azure_api_key = embedding_configer.azure_api_key
if hasattr(embedding_configer, "resource_name"):
self.resource_name = embedding_configer.resource_name
return self
def _initialize_clients(self) -> None:
if not self.azure_api_key:
raise Exception("AZURE_OPENAI_API_KEY is missing")
if not self.resource_name:
raise Exception("AZURE_OPENAI_RESOURCE_NAME is missing")
if not self.azure_api_version:
raise Exception("AZURE_API_VERSION is missing")
if self.client is None:
self.client = AzureOpenAI(
api_key=self.azure_api_key,
api_version=self.azure_api_version,
azure_endpoint=f"https://{self.resource_name}.openai.azure.com"
)
if self.async_client is None:
self.async_client = AsyncAzureOpenAI(
api_key=self.azure_api_key,
api_version=self.azure_api_version,
azure_endpoint=f"https://{self.resource_name}.openai.azure.com"
)
@@ -0,0 +1,8 @@
name: 'azureopenai_embedding'
description: 'embedding use azure openai api'
embedding_model_name: 'text-embedding-ada-002'
metadata:
type: 'EMBEDDING'
module: 'agentuniverse.agent.action.knowledge.embedding.azureopenai_embedding'
class: 'AzureOpenAIEmbedding'
@@ -0,0 +1,166 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/6/12 11:43
# @Author : wangchongshi
# @Email : wangchongshi.wcs@antgroup.com
# @FileName: dashscope_embedding.py
import aiohttp
import requests
from typing import List, Generator, Optional
from pydantic import Field
import json
from agentuniverse.base.util.env_util import get_from_env
from agentuniverse.agent.action.knowledge.embedding.embedding import Embedding
# Dashscope support max 25 string in one batch, each string max tokens is 2048.
DASHSCOPE_MAX_BATCH_SIZE = 25
DASHSCOPE_EMBEDDING_URL = "https://dashscope.aliyuncs.com/api/v1/services/embeddings/text-embedding/text-embedding"
def batched(inputs: List,
batch_size: int = DASHSCOPE_MAX_BATCH_SIZE) -> Generator[List, None, None]:
# Split input string list, due to dashscope support 25 strings in one call.
for i in range(0, len(inputs), batch_size):
yield inputs[i:i + batch_size]
class DashscopeEmbedding(Embedding):
"""The Dashscope embedding class."""
dashscope_api_key: Optional[str] = Field(
default_factory=lambda: get_from_env("DASHSCOPE_API_KEY")
)
def get_embeddings(self, texts: List[str], **kwargs) -> List[List[float]]:
"""
Retrieve text embeddings for a list of input texts.
This function interfaces with the DashScope embedding API to obtain
embeddings for a batch of input texts. It handles batching of input texts
to ensure efficient API calls. Each text is processed using the specified
embedding model.
Args:
texts (List[str]): A list of input texts to be embedded.
Returns:
List[List[float]]: A list of embeddings corresponding to the input texts.
Raises:
Exception: If the API call to DashScope fails, an exception is raised with
the respective error code and message.
"""
def post(post_params):
response = requests.post(
url=DASHSCOPE_EMBEDDING_URL,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {self.dashscope_api_key}"
},
data=json.dumps(post_params, ensure_ascii=False).encode(
"utf-8"),
timeout=300
)
resp_json = response.json()
return resp_json
if not self.dashscope_api_key:
raise Exception("No DASHSCOPE_API_KEY in your environment.")
result = []
post_params = {
"model": self.embedding_model_name,
"input": {},
"parameters": {
}
}
if self.embedding_model_name == "text-embedding-v3":
post_params["parameters"][
"dimension"] = self.embedding_dims if self.embedding_dims else 1024
post_params["parameters"][
"output_type"] = kwargs["output_type"] if "output_type" in kwargs else "dense"
post_params["parameters"]["text_type"] = kwargs["text_type"] if "text_type" in kwargs else "document"
for batch in batched(texts):
post_params["input"]["texts"] = batch
resp_json: dict = post(post_params)
data = resp_json.get("output")
if data:
data = data["embeddings"]
batch_result = [d['embedding'] for d in data if 'embedding' in d]
result += batch_result
else:
error_code = resp_json.get("code", "")
error_message = resp_json.get("message", "")
raise Exception(f"Failed to call dashscope embedding api, "
f"error code:{error_code}, "
f"error message:{error_message}")
return result
async def async_get_embeddings(self, texts: List[str], **kwargs) -> List[List[float]]:
"""
Async version of get_embeddings.
This function interfaces with the DashScope embedding API to obtain
embeddings for a batch of input texts. It handles batching of input texts
to ensure efficient API calls. Each text is processed using the specified
embedding model.
Args:
texts (List[str]): A list of input texts to be embedded.
Returns:
List[List[float]]: A list of embeddings corresponding to the input texts.
Raises:
Exception: If the API call to DashScope fails, an exception is raised with
the respective error code and message.
"""
async def async_post(post_params):
async with aiohttp.ClientSession() as session:
async with await session.post(
url=DASHSCOPE_EMBEDDING_URL,
headers={
"Content-Type": "application/json",
"Authorization": f"Bearer {self.dashscope_api_key}"
},
data=json.dumps(post_params, ensure_ascii=False).encode(
"utf-8"),
timeout=300,
) as resp:
resp_json = await resp.json()
return resp_json
if not self.dashscope_api_key:
raise Exception("No DASHSCOPE_API_KEY in your environment.")
result = []
post_params = {
"model": self.embedding_model_name,
"input": {},
"parameters": {
"text_type": "query"
}
}
if self.embedding_model_name == "text-embedding-v3":
post_params["parameters"][
"dimension"] = self.embedding_dims if self.embedding_dims else 1024
post_params["parameters"][
"output_type"] = kwargs[
"output_type"] if "output_type" in kwargs else "dense"
post_params["parameters"]["text_type"] = kwargs[
"text_type"] if "text_type" in kwargs else "document"
for batch in batched(texts):
post_params["input"]["texts"] = batch
resp_json: dict = await async_post(post_params)
data = resp_json.get("output")
if data:
data = data["embeddings"]
batch_result = [d['embedding'] for d in data if
'embedding' in d]
result += batch_result
else:
error_code = resp_json.get("code", "")
error_message = resp_json.get("message", "")
raise Exception(f"Failed to call dashscope embedding api, "
f"error code:{error_code}, "
f"error message:{error_message}")
return result
@@ -0,0 +1,7 @@
name: 'dashscope_embedding'
description: 'embedding use dashscope api'
embedding_model_name: 'text-embedding-v2'
metadata:
type: 'EMBEDDING'
module: 'agentuniverse.agent.action.knowledge.embedding.dashscope_embedding'
class: 'DashscopeEmbedding'
@@ -0,0 +1,102 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2025/02/15 23:35
# @Author : zhouxiaoji
# @Email : zh_xiaoji@qq.com
# @FileName: doubao_embedding.py
from typing import Any, List, Optional
from pydantic import Field
from agentuniverse.base.util.env_util import get_from_env
from agentuniverse.agent.action.knowledge.embedding.embedding import Embedding
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
SUPPORTED_DIMENSIONS = {512, 1024, 2048}
class DoubaoEmbedding(Embedding):
"""The Doubao embedding class using Volcengine Ark Runtime."""
ark_api_key: Optional[str] = Field(
default_factory=lambda: get_from_env("ARK_API_KEY"))
endpoint_id: Optional[str] = Field(
default_factory=lambda: get_from_env("ARK_ENDPOINT_ID"))
client: Optional[Any] = None
embedding_dims: Optional[int] = None
def get_embeddings(self, texts: List[str], **kwargs) -> List[List[float]]:
"""
Retrieve text embeddings for a list of input texts using Doubao API.
Args:
texts (List[str]): A list of input texts to be embedded.
Returns:
List[List[float]]: A list of embeddings corresponding to the input texts.
Raises:
Exception: If the API call fails or if required configuration is missing.
"""
if not self.client:
if not self.ark_api_key:
raise ValueError("ARK_API_KEY is required but not set")
try:
from volcenginesdkarkruntime import Ark
except ImportError:
raise ImportError(
"Ark is required. Install with: pip install volcengine-python-sdk[ark]"
)
self.client = Ark(api_key=self.ark_api_key)
if not self.endpoint_id:
raise ValueError("endpoint_id is required but not set")
def sliced_norm_l2(vec: List[float]) -> List[float]:
if self.embedding_dims not in SUPPORTED_DIMENSIONS:
raise ValueError(
f"Unsupported embedding dimension: {self.embedding_dims}. "
f"Supported dimensions are: {', '.join(SUPPORTED_DIMENSIONS)}"
)
import numpy as np
norm = float(np.linalg.norm(vec[:self.embedding_dims]))
return [v / norm for v in vec[:self.embedding_dims]]
try:
response = self.client.embeddings.create(model=self.endpoint_id,
input=texts)
if self.embedding_dims is None:
return [data.embedding for data in response.data]
return [sliced_norm_l2(data.embedding) for data in response.data]
except Exception as e:
raise Exception(
f"Failed to get embedding from Doubao API: {str(e)}")
async def async_get_embeddings(self, texts: List[str],
**kwargs) -> List[List[float]]:
return self.get_embeddings(texts)
def _initialize_by_component_configer(
self, embedding_configer: ComponentConfiger) -> 'Embedding':
"""Initialize the embedding by the ComponentConfiger object.
Args:
embedding_configer(ComponentConfiger): A configer contains embedding configuration.
Returns:
Embedding: A DoubaoEmbedding instance.
"""
super()._initialize_by_component_configer(embedding_configer)
if hasattr(embedding_configer, "ark_api_key"):
self.ark_api_key = embedding_configer.ark_api_key
if hasattr(embedding_configer, "endpoint_id"):
self.endpoint_id = embedding_configer.endpoint_id
if hasattr(embedding_configer, "embedding_dims"):
self.embedding_dims = embedding_configer.embedding_dims
if self.ark_api_key:
try:
from volcenginesdkarkruntime import Ark
except ImportError:
raise ImportError(
"Ark is required. Install with: pip install volcengine-python-sdk[ark]"
)
self.client = Ark(api_key=self.ark_api_key)
return self
@@ -0,0 +1,9 @@
name: 'doubao_embedding'
description: 'embedding use doubao'
endpoint_id: ''
ark_api_key: ''
embedding_dims: 1024
metadata:
type: 'EMBEDDING'
module: 'agentuniverse.agent.action.knowledge.embedding.doubao_embedding'
class: 'DoubaoEmbedding'
@@ -0,0 +1,64 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/3/18 19:18
# @Author : wangchongshi
# @Email : wangchongshi.wcs@antgroup.com
# @FileName: embedding.py
from abc import abstractmethod
from typing import List, Optional
from langchain_core.embeddings import Embeddings as LCEmbeddings
from agentuniverse.base.component.component_base import ComponentEnum
from agentuniverse.base.component.component_base import ComponentBase
from agentuniverse.base.config.component_configer.component_configer import \
ComponentConfiger
class Embedding(ComponentBase):
"""The basic class for embedding.
Attributes:
embedding_model_name (Optional[str]): The name of the embedding model.
"""
component_type: ComponentEnum = ComponentEnum.EMBEDDING
name: Optional[str] = None
description: Optional[str] = None
embedding_model_name: Optional[str] = None
embedding_dims: Optional[int] = None
@abstractmethod
def get_embeddings(self, text: List[str], **kwargs) -> List[List[float]]:
"""Get embeddings."""
@abstractmethod
async def async_get_embeddings(self, texts: List[str], **kwargs) -> List[
List[float]]:
"""Asynchronously get embeddings."""
def as_langchain(self) -> LCEmbeddings:
"""Convert the agentUniverse(aU) embedding class to the langchain embedding class."""
pass
def _initialize_by_component_configer(self,
embedding_configer: ComponentConfiger) \
-> 'Embedding':
"""Initialize the embedding by the ComponentConfiger object.
Args:
embedding_configer(ComponentConfiger): A configer contains embedding
basic info.
Returns:
Embedding: A embedding instance.
"""
if embedding_configer.name:
self.name = embedding_configer.name
if embedding_configer.description:
self.description = embedding_configer.description
if hasattr(embedding_configer, "embedding_dims"):
self.embedding_dims = embedding_configer.embedding_dims
if hasattr(embedding_configer, "embedding_model_name"):
self.embedding_model_name = embedding_configer.embedding_model_name
return self
@@ -0,0 +1,21 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/7/23 11:28
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: embedding_manager.py
from agentuniverse.base.annotation.singleton import singleton
from agentuniverse.base.component.component_enum import ComponentEnum
from agentuniverse.base.component.component_manager_base import ComponentManagerBase
from agentuniverse.agent.action.knowledge.embedding.embedding import Embedding
@singleton
class EmbeddingManager(ComponentManagerBase[Embedding]):
"""A singleton manager class of the embedding."""
def __init__(self):
super().__init__(ComponentEnum.EMBEDDING)
@@ -0,0 +1,100 @@
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
from typing import List, Any
from langchain_core.embeddings import Embeddings as LCEmbeddings
from pydantic import Field
from typing_extensions import Optional
from agentuniverse.agent.action.knowledge.embedding.embedding import Embedding
from agentuniverse.base.util.env_util import get_from_env
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
# @Time : 2025/2/13 12:10
# @Author : wozhapen
# @mail : wozhapen@gmail.com
# @FileName :gemini_embedding.py
class GeminiEmbedding(Embedding):
"""Gemini Embedding class that inherits from the base Embedding class."""
client: Any = None
gemini_api_key: Optional[str] = Field(default_factory=lambda: get_from_env("GOOGLE_API_KEY"))
def get_embeddings(self, texts: List[str], **kwargs) -> List[List[float]]:
"""Get embeddings for a list of texts using the Gemini API."""
if not self.client:
if not self.gemini_api_key:
raise ValueError("GOOGLE_API_KEY is required but not set")
try:
from google import genai
self.client = genai.Client(api_key=self.gemini_api_key)
except ImportError as e:
raise ImportError(
"genai is required. Install with: pip install google-genai"
) from e
model_name = self.embedding_model_name or "text-embedding-004" # default model
try:
response = self.client.models.embed_content(
model=model_name,
contents=texts,
# gemini default 768, and only support 768
# config=EmbedContentConfig(output_dimensionality=(self.embedding_dims or 768))
)
return [embedding.values for embedding in response.embeddings]
except Exception as e:
print(f"Error generating embedding for text: {texts}. Error: {e}")
# Handle the error appropriately, e.g., return a zero vector or raise an exception
raise ValueError(e)
async def async_get_embeddings(self, texts: List[str], **kwargs) -> List[List[float]]:
"""Asynchronously get embeddings for a list of texts using the Gemini API."""
# This implementation is synchronous because the Gemini API does not currently offer an official asynchronous client for embedding.
# Consider implementing async batching or utilizing a ThreadPoolExecutor to wrap the synchronous call for better concurrency.
return self.get_embeddings(texts, **kwargs)
def as_langchain(self) -> LCEmbeddings:
"""Convert to a Langchain Embedding class."""
# This can be implemented to return an instance of a custom class extending from `langchain_core.embeddings.Embeddings`.
# However, since we are already using `google.generativeai` directly, this might be redundant.
class GeminiLangchainEmbedding(LCEmbeddings):
"""Wrapper for Gemini Embeddings to conform to Langchain's Embeddings interface."""
gemini_embedding: GeminiEmbedding # Add an instance of GeminiEmbedding
def __init__(self, gemini_embedding: GeminiEmbedding, **kwargs):
super().__init__(**kwargs) # Initialize the parent class
self.gemini_embedding = gemini_embedding # Store the GeminiEmbedding instance
def embed_documents(self, texts: List[str]) -> List[List[float]]:
"""Embed a list of documents."""
return self.gemini_embedding.get_embeddings(texts)
def embed_query(self, text: str) -> List[float]:
"""Embed a single query."""
return self.gemini_embedding.get_embeddings([text])[0]
return GeminiLangchainEmbedding(gemini_embedding=self) # Pass the instance of GeminiEmbedding
def _initialize_by_component_configer(self, embedding_configer: ComponentConfiger) -> 'Embedding':
super()._initialize_by_component_configer(embedding_configer)
if hasattr(embedding_configer, "gemini_api_key"):
self.gemini_api_key = embedding_configer.gemini_api_key
# Initialize client if API key is available
if self.gemini_api_key:
try:
from google import genai
self.client = genai.Client(api_key=self.gemini_api_key)
except ImportError as e:
raise ImportError(
"genai is required. Install with: pip install google-genai"
) from e
except Exception as e:
raise ValueError(f"Failed to initialize Gemini client: {str(e)}")
return self
@@ -0,0 +1,7 @@
name: 'gemini_embedding'
description: 'embedding use gemini'
embedding_model_name: 'text-embedding-004'
metadata:
type: 'EMBEDDING'
module: 'agentuniverse.agent.action.knowledge.embedding.gemini_embedding'
class: 'GeminiEmbedding'
@@ -0,0 +1,153 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
#
# @Time : 2025-10-05 21:40 PM
# @Author : Cascade AI
# @Email : cascade@windsurf.ai
# @FileName: ollama_embedding.py
from typing import Any, Optional, List
from pydantic import Field
import httpx
import asyncio
from agentuniverse.base.util.env_util import get_from_env
from agentuniverse.agent.action.knowledge.embedding.embedding import Embedding
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
class OllamaEmbedding(Embedding):
"""The Ollama embedding class."""
ollama_base_url: Optional[str] = Field(
default_factory=lambda: get_from_env("OLLAMA_BASE_URL") or "http://localhost:11434")
ollama_api_key: Optional[str] = Field(
default_factory=lambda: get_from_env("OLLAMA_API_KEY"))
embedding_model_name: Optional[str] = None
embedding_dims: Optional[int] = None
timeout: Optional[int] = Field(default=30)
client: Any = None
async_client: Any = None
def get_embeddings(self, texts: List[str], **kwargs) -> List[List[float]]:
"""
Retrieve text embeddings for a list of input texts using Ollama API.
Args:
texts (List[str]): A list of input texts to be embedded.
Returns:
List[List[float]]: A list of embeddings corresponding to the input texts.
Raises:
Exception: If the API call fails or if required configuration is missing.
"""
self._initialize_clients()
try:
embeddings = []
for text in texts:
response = self.client.post(
f"{self.ollama_base_url}/api/embeddings",
json={
"model": self.embedding_model_name,
"prompt": text
},
timeout=self.timeout
)
response.raise_for_status()
result = response.json()
embeddings.append(result["embedding"])
return embeddings
except Exception as e:
raise Exception(f"Failed to get embeddings: {e}")
async def async_get_embeddings(self, texts: List[str], **kwargs) -> List[List[float]]:
"""
Retrieve text embeddings for a list of input texts using Ollama API asynchronously.
Args:
texts (List[str]): A list of input texts to be embedded.
Returns:
List[List[float]]: A list of embeddings corresponding to the input texts.
Raises:
Exception: If the API call fails or if required configuration is missing.
"""
self._initialize_clients()
try:
async def get_single_embedding(text: str) -> List[float]:
response = await self.async_client.post(
f"{self.ollama_base_url}/api/embeddings",
json={
"model": self.embedding_model_name,
"prompt": text
},
timeout=self.timeout
)
response.raise_for_status()
result = response.json()
return result["embedding"]
tasks = [get_single_embedding(text) for text in texts]
embeddings = await asyncio.gather(*tasks)
return embeddings
except Exception as e:
raise Exception(f"Failed to get embeddings: {e}")
def as_langchain(self) -> Any:
"""
Convert the OllamaEmbedding instance to a LangChain OllamaEmbeddings instance.
"""
self._initialize_clients()
try:
from langchain_community.embeddings import OllamaEmbeddings
return OllamaEmbeddings(
base_url=self.ollama_base_url,
model=self.embedding_model_name
)
except ImportError:
raise Exception("langchain_community is required for LangChain integration")
def _initialize_by_component_configer(self, embedding_configer: ComponentConfiger) -> 'Embedding':
"""
Initialize the embedding by the ComponentConfiger object.
Args:
embedding_configer(ComponentConfiger): A configer contains embedding configuration.
Returns:
Embedding: A OllamaEmbedding instance.
"""
super()._initialize_by_component_configer(embedding_configer)
if hasattr(embedding_configer, "ollama_base_url"):
self.ollama_base_url = embedding_configer.ollama_base_url
if hasattr(embedding_configer, "ollama_api_key"):
self.ollama_api_key = embedding_configer.ollama_api_key
if hasattr(embedding_configer, "timeout"):
self.timeout = embedding_configer.timeout
return self
def _initialize_clients(self) -> None:
if not self.ollama_base_url:
raise Exception("OLLAMA_BASE_URL is missing")
if not self.embedding_model_name:
raise Exception("embedding_model_name is missing")
headers = {}
if self.ollama_api_key:
headers["Authorization"] = f"Bearer {self.ollama_api_key}"
if self.client is None:
self.client = httpx.Client(
base_url=self.ollama_base_url,
headers=headers,
timeout=self.timeout
)
if self.async_client is None:
self.async_client = httpx.AsyncClient(
base_url=self.ollama_base_url,
headers=headers,
timeout=self.timeout
)
@@ -0,0 +1,8 @@
name: 'ollama_embedding'
description: 'embedding use ollama api with support for mxbai-embed-large, nomic-embed-text, all-minilm models'
embedding_model_name: 'mxbai-embed-large'
metadata:
type: 'EMBEDDING'
module: 'agentuniverse.agent.action.knowledge.embedding.ollama_embedding'
class: 'OllamaEmbedding'
@@ -0,0 +1,117 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/3/19 11:43
# @Author : wangchongshi
# @Email : wangchongshi.wcs@antgroup.com
# @FileName: openai_embedding.py
from typing import List, Optional, Any
from langchain_community.embeddings.openai import OpenAIEmbeddings
from openai import OpenAI, AsyncOpenAI, BadRequestError
from pydantic import Field
from agentuniverse.agent.action.knowledge.embedding.embedding import Embedding
from agentuniverse.base.util.env_util import get_from_env
from agentuniverse.base.config.component_configer.component_configer import \
ComponentConfiger
class OpenAIEmbedding(Embedding):
"""The openai embedding class."""
openai_client_args: Optional[dict] = None
openai_api_key: Optional[str] = Field(default_factory=lambda: get_from_env("OPENAI_API_KEY"))
client: Any = None
async_client: Any = None
dimensions: Optional[int] = None
def get_embeddings(self, texts: List[str]) -> List[List[float]]:
"""Get the OpenAI embeddings.
Note:
The `embedding_model_name` parameter of the openai embedding class must be provided.
The `dimensions` parameter of the openai embedding class is optional.
Args:
texts (List[str]): A list of texts that need to be embedded.
Returns:
List[List[float]]: Each text gets a float list, and the result is a list of the results for each text.
Raises:
ValueError: If texts exceed the embedding model token limit or missing some required parameters.
"""
self.client = OpenAI(api_key=self.openai_api_key, **self.openai_client_args or {})
if self.embedding_model_name is None:
raise ValueError("Must provide `embedding_model_name`")
try:
if self.dimensions:
response = self.client.embeddings.create(input=texts, model=self.embedding_model_name,
dimensions=self.dimensions)
else:
response = self.client.embeddings.create(input=texts, model=self.embedding_model_name)
# Extract the embedding data from the response
data = response.data
# Return the embeddings as a list of lists of floats
return [embedding.embedding for embedding in data]
except BadRequestError as e:
raise ValueError(e.message)
async def async_get_embeddings(self, texts: List[str]) -> List[List[float]]:
"""Asynchronously get the OpenAI embeddings.
Note:
The `embedding_model_name` parameter of the openai embedding class must be provided.
The `dimensions` parameter of the openai embedding class is optional.
Args:
texts (List[str]): A list of texts that need to be embedded.
Returns:
List[List[float]]: Each text gets a float list, and the result is a list of the results for each text.
Raises:
ValueError: If texts exceed the embedding model token limit or missing some required parameters.
"""
self.async_client = AsyncOpenAI(api_key=self.openai_api_key, **self.openai_client_args or {})
if self.embedding_model_name is None:
raise ValueError("Must provide `embedding_model_name`")
try:
if self.dimensions:
response = await self.async_client.embeddings.create(input=texts, model=self.embedding_model_name,
dimensions=self.dimensions)
else:
response = await self.async_client.embeddings.create(input=texts, model=self.embedding_model_name)
# Extract the embedding data from the response
data = response.data
# Return the embeddings as a list of lists of floats
return [embedding.embedding for embedding in data]
except BadRequestError as e:
raise ValueError(e.message)
def as_langchain(self) -> OpenAIEmbeddings:
"""Convert the agentUniverse(aU) openai embedding class to the langchain openai embedding class."""
return OpenAIEmbeddings(openai_api_key=self.openai_api_key,
client=self.client.embeddings, async_client=self.async_client.embeddings)
def _initialize_by_component_configer(self,
embedding_configer: ComponentConfiger) \
-> 'Embedding':
"""Initialize the embedding by the ComponentConfiger object.
Args:
embedding_configer(ComponentConfiger): A configer contains embedding
basic info.
Returns:
Embedding: A embedding instance.
"""
super()._initialize_by_component_configer(embedding_configer)
if hasattr(embedding_configer, "embedding_dims"):
self.dimensions = embedding_configer.embedding_dims
if hasattr(embedding_configer, "openai_client_args"):
self.openai_client_args = embedding_configer.openai_client_args
return self
@@ -0,0 +1,7 @@
name: 'openai_embedding'
description: 'embedding use openai api'
embedding_model_name: 'text-embedding-v2'
metadata:
type: 'EMBEDDING'
module: 'agentuniverse.agent.action.knowledge.embedding.openai_embedding'
class: 'OpenAIEmbedding'
@@ -0,0 +1,343 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
import asyncio
# @Time : 2024/3/22 15:44
# @Author : wangchongshi
# @Email : wangchongshi.wcs@antgroup.com
# @FileName: knowledge.py
import os
import re
import traceback
from copy import deepcopy
from typing import Optional, Dict, List, Any
from concurrent.futures import wait, ALL_COMPLETED
from langchain_core.utils.json import parse_json_markdown
from langchain.tools import Tool as LangchainTool
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.agent.action.knowledge.store.store_manager import StoreManager
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor import DocProcessor
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor_manager import DocProcessorManager
from agentuniverse.agent.action.knowledge.query_paraphraser.query_paraphraser import QueryParaphraser
from agentuniverse.agent.action.knowledge.query_paraphraser.query_paraphraser_manager import QueryParaphraserManager
from agentuniverse.agent.action.knowledge.rag_router.rag_router_manager import RagRouterManager
from agentuniverse.agent.action.knowledge.reader.reader import Reader
from agentuniverse.agent.action.knowledge.reader.reader_manager import ReaderManager
from agentuniverse.base.annotation.trace import trace_knowledge
from agentuniverse.base.component.component_base import ComponentBase
from agentuniverse.base.component.component_enum import ComponentEnum
from agentuniverse.base.util.logging.logging_util import LOGGER
from agentuniverse.agent_serve.web.thread_with_result import ThreadPoolExecutorWithReturnValue
class Knowledge(ComponentBase):
"""
The basic class for the knowledge model.
Attributes:
name (str): The name of the knowledge.
description (str): The description of the knowledge.
stores (List[str]): The stores for the knowledge, which are used to store knowledge
and provide retrieval capabilities, such as ChromaDB store, Redis Store or Qdrant Store.
query_paraphrasers (List[str]): Query paraphrasers used to paraphrase the original query string,
such as extracting keywords and splitting into sub-queries.
insert_processors (List[str]): DocProcessors used in the knowledge insertion step,
such as text splitter and text cleaner.
rag_router (str): RAG router used to decide which stores to use in
the RAG step.
post_processors (List[str]): DocProcessors used in the RAG step to process retrieved
documents, such as reranking and filtering.
readers (Dict[str, str]): The readers of the knowledge, which are used to load data and generate knowledge.
Each reader refers to a specific file type.
insert_executor (ThreadPoolExecutor): Used for performing insert and search
operations concurrently in multiple stores.
ext_info (Optional[Dict]): The extended information of the knowledge.
"""
class Config:
arbitrary_types_allowed = True
name: str = ""
description: Optional[str] = None
stores: List[str] = []
query_paraphrasers: List[str] = []
insert_processors: List[str] = []
update_processors: List[str] = []
rag_router: str = "base_router"
post_processors: List[str] = []
readers: Dict[str, str] = dict()
insert_executor: Optional[ThreadPoolExecutorWithReturnValue] = None
query_executor: Optional[ThreadPoolExecutorWithReturnValue] = None
tracing: Optional[bool] = None
ext_info: Optional[Dict] = None
def __init__(self, **kwargs):
super().__init__(component_type=ComponentEnum.KNOWLEDGE, **kwargs)
self.insert_executor = ThreadPoolExecutorWithReturnValue(
max_workers=5,
thread_name_prefix="Knowledge store"
)
self.query_executor = ThreadPoolExecutorWithReturnValue(
max_workers=10,
thread_name_prefix="Knowledge query"
)
def _load_data(self, *args: Any, **kwargs: Any) -> List[Document]:
# check if source is a local file or remote url
if kwargs.get("source_path"):
source_path = kwargs.get("source_path")
else:
raise Exception("No file to load.")
url_pattern = re.compile(
r'^(https?:\/\/)?'
r'((([a-zA-Z0-9]{1,256}\.[a-zA-Z0-9]{1,6})|'
r'(\d{1,3}\.){3}\d{1,3})'
r'(:\d{1,5})?)'
r'(\/[a-zA-Z0-9@:%._\+~#=]*)*\/?'
r'(\?[a-zA-Z0-9@:%._\+~#&//=]*)?$'
)
if url_pattern.match(source_path):
source_type = "url"
elif os.path.isfile(source_path):
source_type = os.path.splitext(source_path)[1][1:]
else:
raise Exception(f"Knowledge load data error: Unknown source type:{source_path}")
if source_type in self.readers:
reader = ReaderManager().get_instance_obj(self.readers[source_type])
else:
reader = ReaderManager().get_file_default_reader(source_type)
return reader.load_data(source_path)
def _insert_process(self, origin_docs: List[Document]) -> List[Document]:
for _processor_code in self.insert_processors:
doc_processor: DocProcessor = DocProcessorManager().get_instance_obj(_processor_code)
origin_docs = doc_processor.process_docs(origin_docs)
return origin_docs
def _update_process(self, origin_docs: List[Document]) -> List[Document]:
for _processor_code in self.update_processors:
doc_processor: DocProcessor = DocProcessorManager().get_instance_obj(_processor_code)
origin_docs = doc_processor.process_docs(origin_docs)
return origin_docs
def _rag_post_process(self, origin_docs: List[Document], query: Query):
for _processor_code in self.post_processors:
doc_processor: DocProcessor = DocProcessorManager().get_instance_obj(_processor_code)
origin_docs = doc_processor.process_docs(origin_docs, query=query)
return origin_docs
def _paraphrase_query(self, origin_query: Query) -> Query:
for _paraphraser_code in self.query_paraphrasers:
query_paraphraser: QueryParaphraser = QueryParaphraserManager().get_instance_obj(
_paraphraser_code)
origin_query = query_paraphraser.query_paraphrase(origin_query)
return origin_query
def insert_knowledge(self, **kwargs) -> None:
"""Insert the knowledge.
Load data by the reader and insert the documents into the store.
"""
document_list: List[Document] = self._load_data(**kwargs)
document_list = self._insert_process(document_list)
futures = []
if "stores" in kwargs:
stores = kwargs["stores"]
else:
stores = self.stores
for _store_code in stores:
futures.append(
self.insert_executor.submit(
StoreManager().get_instance_obj(_store_code).insert_document,
document_list))
wait(futures, return_when=ALL_COMPLETED)
for future in futures:
try:
future.result()
except Exception as e:
traceback.print_exc()
LOGGER.error(f"Exception occurred in knowledge insert: {e}")
LOGGER.info("Knowledge insert complete.")
def update_knowledge(self, **kwargs) -> None:
"""Update the knowledge.
Load data by the reader and update the documents into the store.
"""
document_list: List[Document] = self._load_data(**kwargs)
document_list = self._update_process(document_list)
futures = []
if "stores" in kwargs:
stores = kwargs["stores"]
else:
stores = self.stores
for _store_code in stores:
futures.append(
self.insert_executor.submit(
StoreManager().get_instance_obj(_store_code).update_document,
document_list))
wait(futures, return_when=ALL_COMPLETED)
for future in futures:
try:
future.result()
except Exception as e:
traceback.print_exc()
LOGGER.error(f"Exception occurred in knowledge update: {e}")
LOGGER.info("Knowledge update complete.")
def _route_rag(self, query: Query):
return RagRouterManager().get_instance_obj(self.rag_router).rag_route(query, self.stores)
@trace_knowledge
def query_knowledge(self, **kwargs) -> List[Document]:
"""Query the knowledge.
Query documents from the store and return the results.
"""
query = Query(**kwargs)
query = self._paraphrase_query(query)
query_tasks = self._route_rag(query)
futures = []
for query_task in query_tasks:
futures.append(
self.query_executor.submit(
StoreManager().get_instance_obj(query_task[1]).query,
query_task[0]))
wait(futures, return_when=ALL_COMPLETED)
retrieved_docs = {}
for future in futures:
try:
task_result = future.result()
for _doc in task_result:
if _doc.id not in retrieved_docs:
retrieved_docs[_doc.id] = _doc
except Exception as e:
traceback.print_exc()
LOGGER.error(f"Exception occurred in knowledge query: {e}")
retrieved_docs = list(retrieved_docs.values())
retrieved_docs = self._rag_post_process(retrieved_docs, query)
return retrieved_docs
def to_llm(self, retrieved_docs: List[Document]) -> Any:
"""Transfer list docs to llm input"""
retrieved_texts = [doc.text for doc in retrieved_docs]
return "\n=========================================\n".join(retrieved_texts)
def _initialize_by_component_configer(self,
knowledge_configer: ComponentConfiger) \
-> 'Knowledge':
"""Initialize the reader by the ComponentConfiger object.
Args:
reader_configer(ComponentConfiger): A configer contains reader
basic info.
Returns:
Reader: A reader instance.
"""
if knowledge_configer.name:
self.name = knowledge_configer.name
if knowledge_configer.description:
self.description = knowledge_configer.description
if hasattr(knowledge_configer, "stores"):
self.stores = knowledge_configer.stores
if hasattr(knowledge_configer, "query_paraphrasers"):
self.query_paraphrasers = knowledge_configer.query_paraphrasers
if hasattr(knowledge_configer, "insert_processors"):
self.insert_processors = knowledge_configer.insert_processors
if hasattr(knowledge_configer, "update_processors"):
self.update_processors = knowledge_configer.update_processors
if hasattr(knowledge_configer, "rag_router"):
self.rag_router = knowledge_configer.rag_router
if hasattr(knowledge_configer, "post_processors"):
self.post_processors = knowledge_configer.post_processors
if hasattr(knowledge_configer, "readers"):
self.readers = knowledge_configer.readers
if hasattr(knowledge_configer, "tracing"):
self.tracing = knowledge_configer.tracing
return self
def langchain_query(self, query: str) -> str:
"""Query the knowledge using LangChain.
Query documents from the store and return the results.
"""
parse_query = parse_json_markdown(query)
knowledge = self.query_knowledge(**parse_query)
return "This is Query Result:\n" + self.to_llm(knowledge)
async def async_langchain_query(self, query: str) -> str:
"""Query the knowledge using LangChain.
Query documents from the store and return the results.
"""
parse_query = parse_json_markdown(query)
knowledge = await asyncio.to_thread(self.query_knowledge, **parse_query)
return "This is Query Result:\n" + self.to_llm(knowledge)
def as_langchain_tool(self) -> LangchainTool:
"""Convert the Knowledge object to a LangChain tool.
Returns:
Any: the LangChain tool object
"""
args_description = """
This is a knowledge base tool, which stores the content you may need. To use this tool, you need to give a json string with the following format:
```json
{
"query_str": "<your query here>",
"similarity_top_k": <number of results to return>,
}
```
"""
return LangchainTool(
name=self.name,
description=self.description or '' + args_description,
func=self.langchain_query,
)
async def async_as_langchain_tool(self) -> LangchainTool:
"""Convert the Knowledge object to a LangChain tool.
Returns:
Any: the LangChain tool object
"""
args_description = """
This is a knowledge base tool, which stores the content you may need. To use this tool, you need to give a json string with the following format:
```json
{
"query_str": "<your query here>",
"similarity_top_k": <number of results to return>,
}
```
"""
return LangchainTool(
name=self.name,
description=self.description or '' + args_description,
func=self.async_langchain_query,
)
def create_copy(self):
copied = self.model_copy()
copied.stores = self.stores.copy()
copied.query_paraphrasers = self.query_paraphrasers.copy()
copied.insert_processors = self.insert_processors.copy()
copied.update_processors = self.update_processors.copy()
copied.post_processors = self.post_processors.copy()
copied.readers = deepcopy(self.readers)
if self.ext_info is not None:
copied.ext_info = deepcopy(self.ext_info)
return copied
@@ -0,0 +1,20 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/3/18 11:24
# @Author : wangchongshi
# @Email : wangchongshi.wcs@antgroup.com
# @FileName: knowledge_manager.py
from agentuniverse.agent.action.knowledge.knowledge import Knowledge
from agentuniverse.base.annotation.singleton import singleton
from agentuniverse.base.component.component_enum import ComponentEnum
from agentuniverse.base.component.component_manager_base import ComponentManagerBase
@singleton
class KnowledgeManager(ComponentManagerBase[Knowledge]):
"""The KnowledgeManager class, which is used to manage the knowledge."""
def __init__(self):
"""Initialize the KnowledgeManager."""
super().__init__(ComponentEnum.KNOWLEDGE)
@@ -0,0 +1,7 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/7/24 10:31
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: __init__.py
@@ -0,0 +1,39 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/8/12 15:44
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: query_keyword_extractor.py
from typing import Optional
from agentuniverse.agent.action.knowledge.doc_processor.doc_processor_manager import \
DocProcessorManager
from agentuniverse.agent.action.knowledge.query_paraphraser.query_paraphraser import QueryParaphraser
from agentuniverse.agent.action.knowledge.store.document import Document
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.config.component_configer.component_configer import \
ComponentConfiger
class QueryKeywordExtractor(QueryParaphraser):
keyword_extractor: Optional[str] = "jieba_keyword_extractor"
def query_paraphrase(self, origin_query: Query) -> Query:
keyword_extractor_instance = DocProcessorManager().get_instance_obj(self.keyword_extractor)
keywords = keyword_extractor_instance.process_docs(
[Document(text=origin_query.query_str)]
)[0].keywords
origin_query.keywords.update(keywords)
return origin_query
def _initialize_by_component_configer(self,
query_paraphraser_configer: ComponentConfiger) -> 'QueryParaphraser':
super()._initialize_by_component_configer(query_paraphraser_configer)
if hasattr(query_paraphraser_configer, "keyword_extractor"):
self.keyword_extractor = query_paraphraser_configer.keyword_extractor
return self
@@ -0,0 +1,6 @@
name: 'query_keyword_extractor'
description: 'extract keywords from query origin str'
metadata:
type: 'QUERY_PARAPHRASER'
module: 'agentuniverse.agent.action.knowledge.query_paraphraser.query_keyword_extractor'
class: 'QueryKeywordExtractor'
@@ -0,0 +1,46 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/7/24 10:59
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: query_paraphraser.py
from abc import abstractmethod
from typing import Optional
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.component.component_base import ComponentEnum
from agentuniverse.base.component.component_base import ComponentBase
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
class QueryParaphraser(ComponentBase):
"""The basic class for query paraphraser."""
component_type: ComponentEnum = ComponentEnum.QUERY_PARAPHRASER
name: Optional[str] = None
description: Optional[str] = None
@abstractmethod
def query_paraphrase(self, origin_query: Query) -> Query:
"""Paraphrase the origin query string to different style."""
def _initialize_by_component_configer(self,
query_paraphraser_config: ComponentConfiger) \
-> 'QueryParaphraser':
"""Initialize the QueryParaphraser by the ComponentConfiger object.
Args:
query_paraphraser_config(ComponentConfiger): A configer contains query_paraphraser
basic info.
Returns:
QueryParaphraser: A query_paraphraser instance.
"""
if query_paraphraser_config.name:
self.name = query_paraphraser_config.name
if query_paraphraser_config.description:
self.description = query_paraphraser_config.description
return self
@@ -0,0 +1,20 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/7/24 11:37
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: query_paraphraser_manager.py
from agentuniverse.base.annotation.singleton import singleton
from agentuniverse.base.component.component_enum import ComponentEnum
from agentuniverse.base.component.component_manager_base import ComponentManagerBase
from agentuniverse.agent.action.knowledge.query_paraphraser.query_paraphraser import QueryParaphraser
@singleton
class QueryParaphraserManager(ComponentManagerBase[QueryParaphraser]):
"""A singleton manager class of the QueryParaphraser."""
def __init__(self):
super().__init__(ComponentEnum.QUERY_PARAPHRASER)
@@ -0,0 +1,7 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/7/24 11:59
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: __init__.py
@@ -0,0 +1,19 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/8/13 11:31
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: base_router.py
from typing import List, Tuple
from agentuniverse.agent.action.knowledge.rag_router.rag_router import \
RagRouter
from agentuniverse.agent.action.knowledge.store.query import Query
class BaseRouter(RagRouter):
def _rag_route(self, query: Query, store_list: List[str]) \
-> List[Tuple[Query, str]]:
return [(query, store) for store in store_list]
@@ -0,0 +1,6 @@
name: 'base_router'
description: 'base rag router map query to all store'
metadata:
type: 'RAG_ROUTER'
module: 'agentuniverse.agent.action.knowledge.rag_router.base_router'
class: 'BaseRouter'
@@ -0,0 +1,55 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/8/13 16:25
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: nlu_rag_router.py
import json
from typing import List, Tuple, Optional
from agentuniverse.agent.agent_manager import AgentManager
from agentuniverse.agent.action.knowledge.store.store_manager import StoreManager
from agentuniverse.agent.action.knowledge.rag_router.rag_router import \
RagRouter
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.config.component_configer.component_configer import \
ComponentConfiger
class NluRagRouter(RagRouter):
llm: Optional[dict] = None
agent_name: str = 'nlu_rag_route_agent'
store_amount: int = 1
def _rag_route(self, query: Query, store_list: List[str]) \
-> List[Tuple[Query, str]]:
agent = AgentManager().get_instance_obj(self.agent_name)
if self.llm:
agent.agent_model.profile['llm_model'] = self.llm
store_info = {}
for _store in store_list:
store_info[_store] = StoreManager().get_instance_obj(_store).description
agent_result = agent.run(
query=query.query_str,
store_info=json.dumps(store_info),
store_amount=self.store_amount
)
target_store_list = agent_result.output.split(",")
if len(target_store_list) > self.store_amount:
target_store_list = target_store_list[:self.store_amount]
filtered_store_list = [_store for _store in target_store_list if _store in store_list]
return [(query, store) for store in filtered_store_list]
def _initialize_by_component_configer(self,
rag_router_config: ComponentConfiger) -> 'RagRouter':
super()._initialize_by_component_configer(rag_router_config)
if hasattr(rag_router_config, "llm"):
self.llm = rag_router_config.llm
if hasattr(rag_router_config, "agent_name"):
self.agent_name = rag_router_config.agent_name
if hasattr(rag_router_config, "store_amount"):
self.store_amount = rag_router_config.store_amount
@@ -0,0 +1,52 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/7/24 12:00
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: rag_router.py
from abc import abstractmethod
from typing import List, Optional, Tuple
from agentuniverse.agent.action.knowledge.store.query import Query
from agentuniverse.base.component.component_base import ComponentEnum
from agentuniverse.base.component.component_base import ComponentBase
from agentuniverse.base.config.component_configer.component_configer import ComponentConfiger
class RagRouter(ComponentBase):
"""The basic class for rag router."""
component_type: ComponentEnum = ComponentEnum.RAG_ROUTER
name: Optional[str] = None
description: Optional[str] = None
def rag_route(self, query: Query, store_list: List[str]) \
-> List[Tuple[Query, str]]:
"""Accept query a list of store instance name, and return a list of
query-store pair."""
return self._rag_route(query, store_list)
def _rag_route(self, query: Query, store_list: List[str]) \
-> List[Tuple[Query, str]]:
"""Accept query a list of store instance name, and return a list of
query-store pair."""
pass
def _initialize_by_component_configer(self,
rag_router_config: ComponentConfiger) \
-> 'RagRouter':
"""Initialize the rag router by the ComponentConfiger object.
Args:
rag_router_config(ComponentConfiger): A configer contains rag router
basic info.
Returns:
RagRouter: A rag router instance.
"""
if rag_router_config.name:
self.name = rag_router_config.name
if rag_router_config.description:
self.description = rag_router_config.description
return self
@@ -0,0 +1,20 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/7/25 14:16
# @Author : fanen.lhy
# @Email : fanen.lhy@antgroup.com
# @FileName: rag_router_manager.py
from agentuniverse.base.annotation.singleton import singleton
from agentuniverse.base.component.component_enum import ComponentEnum
from agentuniverse.base.component.component_manager_base import ComponentManagerBase
from agentuniverse.agent.action.knowledge.rag_router.rag_router import RagRouter
@singleton
class RagRouterManager(ComponentManagerBase[RagRouter]):
"""A singleton manager class of the RagRouter."""
def __init__(self):
super().__init__(ComponentEnum.RAG_ROUTER)
@@ -0,0 +1,7 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/4/2 17:13
# @Author : wangchongshi
# @Email : wangchongshi.wcs@antgroup.com
# @FileName: __init__.py
@@ -0,0 +1,65 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2025/9/29
# @FileName: confluence_reader.py
from typing import List, Optional, Dict
from agentuniverse.agent.action.knowledge.reader.reader import Reader
from agentuniverse.agent.action.knowledge.store.document import Document
class ConfluenceReader(Reader):
"""Reader for Atlassian Confluence pages.
Requires:
pip install atlassian-python-api
Credentials:
site_url, username, token must be provided via ext_info or env.
"""
def _load_data(self, page_id: str, ext_info: Optional[Dict] = None) -> List[Document]:
print(f"debugging: ConfluenceReader start load page_id={page_id}")
if not page_id:
raise ValueError("ConfluenceReader requires page_id")
site_url, username, token = self._resolve_cred(ext_info)
try:
from atlassian import Confluence # type: ignore
except Exception:
raise ImportError("Install atlassian-python-api: `pip install atlassian-python-api`")
conf = Confluence(url=site_url, username=username, password=token, cloud=True)
page = conf.get_page_by_id(page_id, expand="body.view,version,metadata.labels")
html = page.get("body", {}).get("view", {}).get("value", "")
text = self._html_to_text(html)
metadata: Dict = {
"source": "confluence",
"page_id": page_id,
"title": page.get("title"),
"version": page.get("version", {}).get("number")
}
if ext_info:
metadata.update(ext_info)
return [Document(text=text, metadata=metadata)]
def _resolve_cred(self, ext_info: Optional[Dict]) -> (str, str, str):
import os
site_url = (ext_info or {}).get("site_url") or os.environ.get("CONFLUENCE_URL")
username = (ext_info or {}).get("username") or os.environ.get("CONFLUENCE_USERNAME")
token = (ext_info or {}).get("token") or os.environ.get("CONFLUENCE_TOKEN")
if not site_url or not username or not token:
raise EnvironmentError("Confluence credentials required: site_url, username, token")
return site_url, username, token
def _html_to_text(self, html: str) -> str:
try:
from bs4 import BeautifulSoup # type: ignore
except Exception:
raise ImportError("Install beautifulsoup4 and lxml for ConfluenceReader")
soup = BeautifulSoup(html, "lxml")
for tag in soup(["script", "style", "noscript"]):
tag.extract()
text = soup.get_text("\n")
return "\n".join([line.strip() for line in text.splitlines() if line.strip()])
@@ -0,0 +1,6 @@
name: 'default_confluence_reader'
description: 'default Confluence reader'
metadata:
type: 'READER'
module: 'agentuniverse.agent.action.knowledge.reader.cloud.confluence_reader'
class: 'ConfluenceReader'
@@ -0,0 +1,72 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2025/9/29
# @FileName: google_docs_reader.py
from typing import List, Optional, Dict
from agentuniverse.agent.action.knowledge.reader.reader import Reader
from agentuniverse.agent.action.knowledge.store.document import Document
class GoogleDocsReader(Reader):
"""Reader for Google Docs via Google Drive export.
Requires:
pip install google-api-python-client google-auth google-auth-oauthlib
Credentials:
Use a service account JSON or OAuth credentials; pass via env or ext_info.
"""
def _load_data(self, doc_id: str, ext_info: Optional[Dict] = None) -> List[Document]:
print(f"debugging: GoogleDocsReader start load doc_id={doc_id}")
if not doc_id:
raise ValueError("GoogleDocsReader requires doc_id")
service = self._build_drive_service(ext_info)
html = self._export_html(service, doc_id)
text = self._html_to_text(html)
metadata: Dict = {"source": "google_docs", "doc_id": doc_id}
if ext_info:
metadata.update(ext_info)
return [Document(text=text, metadata=metadata)]
def _build_drive_service(self, ext_info: Optional[Dict]):
try:
from google.oauth2.service_account import Credentials # type: ignore
from googleapiclient.discovery import build # type: ignore
except Exception:
raise ImportError("Install Google API deps: `pip install google-api-python-client google-auth google-auth-oauthlib`")
import os
scopes = ['https://www.googleapis.com/auth/drive.readonly']
sa_path = (ext_info or {}).get('GOOGLE_SERVICE_ACCOUNT_JSON') or os.environ.get('GOOGLE_SERVICE_ACCOUNT_JSON')
if not sa_path:
raise EnvironmentError("Provide GOOGLE_SERVICE_ACCOUNT_JSON path for service account usage")
creds = Credentials.from_service_account_file(sa_path, scopes=scopes)
return build('drive', 'v3', credentials=creds)
def _export_html(self, drive, file_id: str) -> str:
from googleapiclient.http import MediaIoBaseDownload # type: ignore
import io
print("debugging: GoogleDocsReader exporting as HTML")
request = drive.files().export(fileId=file_id, mimeType='text/html')
fh = io.BytesIO()
downloader = MediaIoBaseDownload(fh, request)
done = False
while done is False:
status, done = downloader.next_chunk()
html = fh.getvalue().decode('utf-8', errors='ignore')
return html
def _html_to_text(self, html: str) -> str:
try:
from bs4 import BeautifulSoup # type: ignore
except Exception:
raise ImportError("Install beautifulsoup4 and lxml for GoogleDocsReader")
soup = BeautifulSoup(html, "lxml")
for tag in soup(["script", "style", "noscript"]):
tag.extract()
text = soup.get_text("\n")
return "\n".join([line.strip() for line in text.splitlines() if line.strip()])
@@ -0,0 +1,6 @@
name: 'default_google_docs_reader'
description: 'default Google Docs reader'
metadata:
type: 'READER'
module: 'agentuniverse.agent.action.knowledge.reader.cloud.google_docs_reader'
class: 'GoogleDocsReader'
@@ -0,0 +1,97 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2025/9/29
# @FileName: notion_reader.py
from typing import List, Optional, Dict
from agentuniverse.agent.action.knowledge.reader.reader import Reader
from agentuniverse.agent.action.knowledge.store.document import Document
class NotionReader(Reader):
"""Reader for Notion pages/databases via Notion API.
Requires:
pip install notion-client
Environment:
NOTION_TOKEN must be provided (or pass via ext_info)
"""
def _load_data(self, page_or_db_id: str, ext_info: Optional[Dict] = None) -> List[Document]:
print(f"debugging: NotionReader start load id={page_or_db_id}")
if not page_or_db_id:
raise ValueError("NotionReader requires a Notion page or database id")
token = None
if ext_info:
token = ext_info.get("NOTION_TOKEN") or ext_info.get("notion_token")
if not token:
import os
token = os.environ.get("NOTION_TOKEN")
if not token:
raise EnvironmentError("NOTION_TOKEN is required for NotionReader")
try:
from notion_client import Client # type: ignore
except Exception:
raise ImportError("Install notion-client: `pip install notion-client`")
client = Client(auth=token)
text_blocks: List[str] = []
metadata: Dict = {"source": "notion", "id": page_or_db_id}
# Try as page
try:
page = client.pages.retrieve(page_id=page_or_db_id)
metadata["type"] = "page"
text_blocks.extend(self._export_page(client, page_or_db_id))
except Exception as e_page:
print(f"debugging: NotionReader page retrieve failed: {e_page}")
# Try as database
try:
metadata["type"] = "database"
for row in client.databases.query(database_id=page_or_db_id).get("results", []):
row_id = row.get("id")
text_blocks.extend(self._export_page(client, row_id))
except Exception as e_db:
raise RuntimeError(f"Failed to read Notion id={page_or_db_id}: {e_db}")
text = "\n\n".join([b for b in text_blocks if b and b.strip()])
if ext_info:
metadata.update(ext_info)
return [Document(text=text, metadata=metadata)]
def _export_page(self, client, page_id: str) -> List[str]:
blocks: List[str] = []
cursor = None
while True:
children = client.blocks.children.list(block_id=page_id, start_cursor=cursor)
for blk in children.get("results", []):
txt = self._block_to_text(blk)
if txt:
blocks.append(txt)
if not children.get("has_more"):
break
cursor = children.get("next_cursor")
return blocks
def _block_to_text(self, block: Dict) -> str:
t = block.get("type")
data = block.get(t, {}) if t else {}
def rich_text_to_str(items: List[Dict]) -> str:
parts: List[str] = []
for it in items or []:
plain = it.get("plain_text") or ""
if plain:
parts.append(plain)
return "".join(parts)
if t in ("paragraph", "heading_1", "heading_2", "heading_3", "quote", "callout", "bulleted_list_item", "numbered_list_item", "to_do", "toggle"):
return rich_text_to_str(data.get("rich_text", []))
if t == "code":
return rich_text_to_str(data.get("rich_text", []))
if t == "table":
return "[table omitted]"
if t == "image":
return "[image]"
return ""
@@ -0,0 +1,6 @@
name: 'default_notion_reader'
description: 'default Notion reader'
metadata:
type: 'READER'
module: 'agentuniverse.agent.action.knowledge.reader.cloud.notion_reader'
class: 'NotionReader'
@@ -0,0 +1,146 @@
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2025/4/10 17:40
# @Author : zhaoyifei
# @Email : 2179709293@qq.com
# @FileName: feishu_reader.py
from selenium import webdriver
from selenium.webdriver.chrome.options import Options
from bs4 import BeautifulSoup
import time
from typing import Dict,List
from agentuniverse.agent.action.knowledge.store.document import Document
class PublicFeishuReader:
"""Feishu public document reader using Selenium
Extracts content from public Feishu documents through web scraping with dynamic rendering support.
Attributes:
driver: Selenium WebDriver instance configured for headless browsing
"""
def __init__(self):
"""Initialize Selenium WebDriver with headless configuration"""
chrome_options = Options()
chrome_options.add_argument("--headless")
chrome_options.add_argument("--disable-gpu")
chrome_options.add_argument("--no-sandbox")
chrome_options.add_argument(
"User-Agent=Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/120.0.0.0 Safari/537.36"
)
self.driver = webdriver.Chrome(options=chrome_options)
def _fetch_document_content(self, url: str) -> str:
"""Fetch Feishu document content after dynamic rendering
Args:
url (str): URL of the public Feishu document
Returns:
str: Extracted document content or empty string on failure
Raises:
RuntimeError: If page loading fails
"""
try:
self.driver.get(url)
# Wait for dynamic content loading
time.sleep(5)
page_source = self.driver.page_source
soup = BeautifulSoup(page_source, 'html.parser')
return self._parse_content(soup)
except Exception as e:
print(f"Error fetching document: {e}")
return ""
def _parse_content(self, soup: BeautifulSoup) -> str:
"""Parse document content and extract meaningful text
Args:
soup (BeautifulSoup): Parsed HTML document object
Returns:
str: Cleaned text content with deduplication
Raises:
ValueError: If document structure is invalid
"""
# Find the body tag
body = soup.find('body')
if not body:
return "Body tag not found"
content = []
# Extract document title
title_tag = soup.find('h1')
if title_tag:
title_text = title_tag.get_text(strip=True)
if title_text:
content.append(f"Title: {title_text}")
# Define irrelevant class names for filtering
irrelevant_classes = ['footer', 'nav', 'navigation', 'header', 'comment', 'help', 'login']
# Try to locate main content container
content_div = soup.find('div', class_='doc-content') # Update class name as needed
if content_div:
# Extract text from content container
for tag in content_div.find_all(['p', 'div', 'span'], recursive=True):
if tag.get('class') and any(cls.lower() in irrelevant_classes for cls in tag.get('class')):
continue
text = tag.get_text(strip=True)
if text and text.strip() and not any(
keyword in text.lower() for keyword in ['login', 'sign up', 'comment', 'help']):
content.append(text)
else:
# Fallback extraction from body
for div in body.find_all('div', recursive=True):
if div.get('class') and any(cls.lower() in irrelevant_classes for cls in div.get('class')):
continue
text = div.get_text(strip=True)
if text and text.strip() and not any(
keyword in text.lower() for keyword in ['login', 'sign up', 'comment', 'help']):
content.append(text)
# Deduplicate while preserving order
unique_content = list(dict.fromkeys(content))
return "\n".join(unique_content) if unique_content else "No meaningful content found"
def load_data(self, url: str) -> List[Document]:
"""Load and process Feishu document data
Args:
url (str): URL of the target document
Returns:
List[Document]: List of documents containing feishu online file content
"""
content = self._fetch_document_content(url)
# If the content is empty, return an empty list
if not content:
return []
# Construct metadata
metadata = {"source": url}
# Create a Document object
document = Document(text=content, metadata=metadata)
# Return a list containing a single Document
return [document]
def __del__(self):
"""Cleanup resources by closing browser instance"""
if hasattr(self, 'driver'):
self.driver.quit()
"""
if __name__ == "__main__":
# Example usage
test_url = "https://www.feishu.cn/docx/SV2JdR5P4odO8AxIhpBcVo1Xncg"
reader = PublicFeishuReader()
data = reader.load_data(test_url)
print(data)
print("Document Summary:", data[0].text)
"""
@@ -0,0 +1,6 @@
name: 'default_feishu_reader'
description: 'default feishu cloud document reader'
metadata:
type: 'READER'
module: 'agentuniverse.agent.action.knowledge.reader.cloud_document.feishu_reader'
class: 'PublicFeishuReader'
@@ -0,0 +1,125 @@
#!/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2025/5/2 17:40
# @Author : KiteSoar
# @Email : hushihao2020x@163.com
# @FileName: yuque_reader.py
import re
import time
import random
import json
import urllib.parse
import requests
from pydantic import ConfigDict
from requests.adapters import HTTPAdapter, Retry
from bs4 import BeautifulSoup
from typing import List, Any, Optional
from agentuniverse.agent.action.knowledge.reader.reader import Reader
from agentuniverse.agent.action.knowledge.store.document import Document
class YuqueReader(Reader):
"""
YuqueReader is a specialized reader designed to fetch and parse content from Yuque
Attributes:
cookies: Cookies for authentication with Yuque.
session: HTTP session with retry support.
"""
model_config = ConfigDict(arbitrary_types_allowed=True)
cookies: Optional[str] = None
session: Optional[requests.Session] = None
def __init__(self, cookies: str = None, **data: Any):
"""Initialize HTTP session with retry support and optional cookies"""
super().__init__(**data)
self.cookies = cookies
self.session = requests.Session()
retries = Retry(total=5, backoff_factor=0.5, status_forcelist=[500,502,503,504])
self.session.mount('https://', HTTPAdapter(max_retries=retries))
def _fetch_url_title(self, url: str) -> str:
"""Fetch page title and clean illegal filename characters"""
headers = {'Cookie': self.cookies} if self.cookies else {}
try:
resp = self.session.get(url, headers=headers, timeout=10)
resp.raise_for_status()
soup = BeautifulSoup(resp.text, 'html.parser')
tag = soup.title
if not tag or not tag.string:
return "Untitled"
title = tag.string.strip()
title = re.sub(r'[\\/:*?"<>|]', '-', title)
return title.replace(' · 语雀', '')
except requests.exceptions.RequestException:
return "Request Error"
def _fetch_page_markdown(self, book_id: str, slug: str) -> str:
"""Fetch markdown source for a single document"""
headers = {'Cookie': self.cookies} if self.cookies else {}
url = f'https://www.yuque.com/api/docs/{slug}?book_id={book_id}&merge_dynamic_data=false&mode=markdown'
resp = self.session.get(url, headers=headers, timeout=20)
if resp.status_code != 200:
print("The document download failed. The page may have been deleted.", book_id, slug)
return ''
data = resp.json().get('data', {})
md = data.get('sourcecode', '')
# Process image references inline
def repl(m):
src = m.group(1)
return f'![]({src})'
return re.sub(r'!\[.*?\]\((.*?)\)', repl, md)
def _load_data(self, url: str) -> List[Document]:
"""Fetch all docs in a Yuque book and return as List[Document]"""
headers = {'Cookie': self.cookies} if self.cookies else {}
try:
resp = self.session.get(url, headers=headers, timeout=10)
resp.raise_for_status()
encoded = re.findall(r'decodeURIComponent\("(.+)"\)\);', resp.text)[0]
docs = json.loads(urllib.parse.unquote(encoded))
except Exception as e:
print(f"Request failed: {e}")
return []
book_title = self._fetch_url_title(url)
# sanitize titles for metadata keys if needed
chars = '/:*?"<>|\n\r'
trans = str.maketrans({c: '_' for c in chars})
documents: List[Document] = []
for item in docs['book']['toc']:
if item['title'] != book_title:
continue
md = self._fetch_page_markdown(str(docs['book']['id']), item['url'])
if not md:
continue
metadata = {
'source': url,
'doc_title': item['title'],
'sanitized_title': item['title'].translate(trans)
}
documents.append(Document(text=md, metadata=metadata))
# Respectful delay
time.sleep(random.uniform(1, 3))
return documents
def __del__(self):
"""Close HTTP session"""
try:
self.session.close()
except:
pass
# if __name__ == '__main__':
# # Example usage
# reader = YuqueReader(cookies=None)
# test_url = "Fill in the publicly accessible Yuque document link"
# docs = reader.load_data(test_url)
# for doc in docs:
# print(f"Title: {doc.metadata['doc_title']}")
# print(doc.text)
@@ -0,0 +1,6 @@
name: 'default_yuque_reader'
description: 'default yuque document reader'
metadata:
type: 'READER'
module: 'agentuniverse.agent.action.knowledge.reader.cloud_document.yuque_reader'
class: 'YuqueReader'
@@ -0,0 +1,13 @@
# !/usr/bin/env python3
# -*- coding:utf-8 -*-
# @Time : 2024/4/2 17:13
# @Author : wangchongshi
# @Email : wangchongshi.wcs@antgroup.com
# @FileName: __init__.py
from .epub_reader import EpubReader
from .xlsx_reader import XlsxReader
from .rar_reader import RarReader
from .zip_reader import ZipReader
from .sevenzip_reader import SevenZipReader

Some files were not shown because too many files have changed in this diff Show More