smartagents-py 0.1.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (27) hide show
  1. smartagents_py-0.1.0/LICENSE +21 -0
  2. smartagents_py-0.1.0/PKG-INFO +214 -0
  3. smartagents_py-0.1.0/README.md +164 -0
  4. smartagents_py-0.1.0/pyproject.toml +53 -0
  5. smartagents_py-0.1.0/setup.cfg +4 -0
  6. smartagents_py-0.1.0/smart_agents/__init__.py +35 -0
  7. smartagents_py-0.1.0/smart_agents/agents/__init__.py +9 -0
  8. smartagents_py-0.1.0/smart_agents/agents/react_agent.py +101 -0
  9. smartagents_py-0.1.0/smart_agents/agents/simple_agent.py +232 -0
  10. smartagents_py-0.1.0/smart_agents/core/__init__.py +13 -0
  11. smartagents_py-0.1.0/smart_agents/core/agent.py +45 -0
  12. smartagents_py-0.1.0/smart_agents/core/config.py +32 -0
  13. smartagents_py-0.1.0/smart_agents/core/llm.py +290 -0
  14. smartagents_py-0.1.0/smart_agents/core/message.py +32 -0
  15. smartagents_py-0.1.0/smart_agents/tools/__init__.py +35 -0
  16. smartagents_py-0.1.0/smart_agents/tools/async_executor.py +148 -0
  17. smartagents_py-0.1.0/smart_agents/tools/base.py +37 -0
  18. smartagents_py-0.1.0/smart_agents/tools/builtin/__init__.py +25 -0
  19. smartagents_py-0.1.0/smart_agents/tools/builtin/calculator.py +102 -0
  20. smartagents_py-0.1.0/smart_agents/tools/builtin/search.py +114 -0
  21. smartagents_py-0.1.0/smart_agents/tools/chain.py +121 -0
  22. smartagents_py-0.1.0/smart_agents/tools/registry.py +112 -0
  23. smartagents_py-0.1.0/smartagents_py.egg-info/PKG-INFO +214 -0
  24. smartagents_py-0.1.0/smartagents_py.egg-info/SOURCES.txt +25 -0
  25. smartagents_py-0.1.0/smartagents_py.egg-info/dependency_links.txt +1 -0
  26. smartagents_py-0.1.0/smartagents_py.egg-info/requires.txt +10 -0
  27. smartagents_py-0.1.0/smartagents_py.egg-info/top_level.txt +1 -0
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2025 edgetalker
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
@@ -0,0 +1,214 @@
1
+ Metadata-Version: 2.4
2
+ Name: smartagents-py
3
+ Version: 0.1.0
4
+ Summary: A lightweight agent framework based on LLM
5
+ Author-email: edgetalker <kevinpan998@gmail.com>
6
+ License: MIT License
7
+
8
+ Copyright (c) 2025 edgetalker
9
+
10
+ Permission is hereby granted, free of charge, to any person obtaining a copy
11
+ of this software and associated documentation files (the "Software"), to deal
12
+ in the Software without restriction, including without limitation the rights
13
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
14
+ copies of the Software, and to permit persons to whom the Software is
15
+ furnished to do so, subject to the following conditions:
16
+
17
+ The above copyright notice and this permission notice shall be included in all
18
+ copies or substantial portions of the Software.
19
+
20
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
21
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
22
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
23
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
24
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
25
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
26
+ SOFTWARE.
27
+ Project-URL: Homepage, https://github.com/edgetalker/smartagents
28
+ Project-URL: Repository, https://github.com/edgetalker/smartagents
29
+ Project-URL: Issues, https://github.com/edgetalker/smartagents/issues
30
+ Keywords: agent,llm,ai,openai
31
+ Classifier: Programming Language :: Python :: 3
32
+ Classifier: Programming Language :: Python :: 3.10
33
+ Classifier: Programming Language :: Python :: 3.11
34
+ Classifier: License :: OSI Approved :: MIT License
35
+ Classifier: Operating System :: OS Independent
36
+ Classifier: Topic :: Scientific/Engineering :: Artificial Intelligence
37
+ Requires-Python: >=3.10
38
+ Description-Content-Type: text/markdown
39
+ License-File: LICENSE
40
+ Requires-Dist: openai>=1.0.0
41
+ Requires-Dist: pydantic>=2.0.0
42
+ Requires-Dist: requests>=2.25.0
43
+ Requires-Dist: python-dotenv>=1.0.0
44
+ Requires-Dist: tavily-python>=0.3.0
45
+ Requires-Dist: google-search-results>=2.4.0
46
+ Provides-Extra: dev
47
+ Requires-Dist: pytest>=7.0.0; extra == "dev"
48
+ Requires-Dist: black>=22.0.0; extra == "dev"
49
+ Dynamic: license-file
50
+
51
+ <div align="center">
52
+
53
+ # 🤖 SmartAgents
54
+
55
+ *从零实现LLM Agent框架 - 教学级实现与工程化实践*
56
+
57
+ [![Python](https://img.shields.io/badge/Python-3.10+-blue.svg)](https://www.python.org/downloads/)
58
+ [![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
59
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
60
+
61
+ [🚀 快速开始](#快速开始) • [📖 文档](docs/) • [🎯 示例](examples/) • [🤝 贡献指南](CONTRIBUTING.md)
62
+
63
+ </div>
64
+
65
+ ---
66
+
67
+ ## ✨ 项目亮点
68
+
69
+ - 🎓 **低耦合架构**: 清晰的模块组织和渐进式实现,适合学习Agent内部机制
70
+ - 🏗️ **工程化实践**: 模块化架构、完整测试、CI/CD流程
71
+ - 🔧 **生产可用**: 支持DeepSeek/OpenAI等多Provider,自动检测服务商
72
+ - 📚 **功能完整**: 内置多种工具调用、工具链、工具异步调用
73
+
74
+ ## 🎬 快速演示
75
+ ```python
76
+ from smart_agents import SimpleAgent
77
+ from smart_agents.llm import SimpleAgentLLM
78
+ from smart_agents.tools import ToolRegistry
79
+ from smart_agents.tools.bulitin import SearchTool
80
+ # 初始化LLM
81
+ llm = SmartAgentLLM()
82
+
83
+ # 初始化工具
84
+ searchTool = SearchTool()
85
+ tool_registry.register_tool(searchTool)
86
+
87
+ # 初始化Agent
88
+ agent = SimpleAgent(
89
+ name="工具增强助手",
90
+ llm=llm,
91
+ system_prompt="你是一个智能助手,可以使用工具来帮助用户。",
92
+ tool_registry=tool_registry,
93
+ enable_tool_calling=True
94
+ )
95
+
96
+ response = agent.run("2026年小米手机最新款是什么,有什么卖点")
97
+ print(f"工具增强助手响应: {response}")
98
+ # 2026年小米手机的最新款型有几个比较主要的系列:
99
+
100
+ # 1. Redmi Note系列:主打千元长续航、耐用抗造,适合长辈、户外、备用机。
101
+ # 2. Redmi K系列:主打电竞性能、性价比旗舰,适合学生、游戏玩家。...
102
+ ```
103
+
104
+ ## 📊 架构设计
105
+ ```
106
+ ┌─────────────────────────────────────────┐
107
+ │ User Interface (API) │
108
+ └──────────────┬──────────────────────────┘
109
+
110
+ ┌──────────────▼──────────────────────────┐
111
+ │ Agent Core (ReAct) │
112
+ │ ┌────────┐ ┌────────┐ ┌──────────┐ │
113
+ │ │Planning│ │Executor│ │Reflexion │ │
114
+ │ └────────┘ └────────┘ └──────────┘ │
115
+ └──────────────┬──────────────────────────┘
116
+
117
+ ┌──────────┼──────────┐
118
+ │ │ │
119
+ ┌───▼───┐ ┌──▼───┐ ┌──▼─────┐
120
+ │Memory │ │Tools │ │LLM Prov│
121
+ │System │ │ │ │ │
122
+ └───────┘ └──────┘ └────────┘
123
+ ```
124
+
125
+ ## 🚀 快速开始
126
+
127
+ ### 安装
128
+ ```bash
129
+ # 使用pip安装
130
+ pip install smart_agents
131
+
132
+ # 或从源码安装
133
+ git clone https://github.com/edgetalker/smart_agents.git
134
+ cd hello-agents
135
+ ```
136
+
137
+ ### 配置
138
+ ```bash
139
+ cp .env.example .env
140
+ # 编辑.env文件,填入API密钥
141
+ ```
142
+
143
+ ## 📖 核心功能
144
+
145
+ ### 1️⃣ ReAct执行循环
146
+ ```python
147
+ # Agent自动进行推理-行动循环
148
+ agent.run("帮我查询AAPL股票价格并分析走势")
149
+
150
+ # 内部执行过程:
151
+ # Thought: 需要先获取股票价格
152
+ # Action: get_stock_price("AAPL")
153
+ # Observation: $178.32
154
+ # Thought: 需要分析历史数据
155
+ # Action: analyze_trend("AAPL", days=30)
156
+ # Observation: 上涨趋势...
157
+ # Final Answer: ...
158
+ ```
159
+
160
+ ### 2️⃣ 向量记忆系统
161
+ ```python
162
+ # 长期记忆存储与检索
163
+ agent.memory.store("用户偏好Python开发")
164
+ relevant = agent.memory.retrieve("编程语言")
165
+ # 自动召回相关上下文
166
+ ```
167
+
168
+ ### 3️⃣ 自定义工具
169
+ ```python
170
+ from smart_agents.tools import Tool
171
+
172
+ @Tool(
173
+ name="database_query",
174
+ description="查询MySQL数据库"
175
+ )
176
+ async def query_db(sql: str) -> str:
177
+ # 你的实现
178
+ return results
179
+ ```
180
+
181
+ ## 🗺️ 开发路线图
182
+
183
+ - [x] 基础Agent框架 (v0.1.0)
184
+ - [x] ReAct执行循环 (v0.2.0)
185
+ - [x] 向量记忆系统 (v0.3.0)
186
+ - [ ] Reflexion自我反思 (v0.4.0)
187
+ - [ ] 多Agent协作 (v0.5.0)
188
+ - [ ] 生产优化与部署 (v1.0.0)
189
+
190
+ ## 🤝 贡献
191
+
192
+ 欢迎提交Issue和Pull Request!
193
+
194
+
195
+ ## 📄 许可证
196
+
197
+ [MIT License](LICENSE) © edgetalker
198
+
199
+ ## 🙏 致谢
200
+
201
+ - DataWhale HelloAgents项目启发
202
+ - MIT 6.5940课程的优化技术
203
+ - LangChain社区的最佳实践
204
+
205
+ ## 📧 联系方式
206
+
207
+ - GitHub: [@edgetalker](https://github.com/edgetalker)
208
+ - Email: kevinpan998@gmail.com
209
+
210
+ ---
211
+
212
+ <div align="center">
213
+ 如果这个项目对你有帮助,请给个⭐️支持一下!
214
+ </div>
@@ -0,0 +1,164 @@
1
+ <div align="center">
2
+
3
+ # 🤖 SmartAgents
4
+
5
+ *从零实现LLM Agent框架 - 教学级实现与工程化实践*
6
+
7
+ [![Python](https://img.shields.io/badge/Python-3.10+-blue.svg)](https://www.python.org/downloads/)
8
+ [![License](https://img.shields.io/badge/License-MIT-green.svg)](LICENSE)
9
+ [![Code style: black](https://img.shields.io/badge/code%20style-black-000000.svg)](https://github.com/psf/black)
10
+
11
+ [🚀 快速开始](#快速开始) • [📖 文档](docs/) • [🎯 示例](examples/) • [🤝 贡献指南](CONTRIBUTING.md)
12
+
13
+ </div>
14
+
15
+ ---
16
+
17
+ ## ✨ 项目亮点
18
+
19
+ - 🎓 **低耦合架构**: 清晰的模块组织和渐进式实现,适合学习Agent内部机制
20
+ - 🏗️ **工程化实践**: 模块化架构、完整测试、CI/CD流程
21
+ - 🔧 **生产可用**: 支持DeepSeek/OpenAI等多Provider,自动检测服务商
22
+ - 📚 **功能完整**: 内置多种工具调用、工具链、工具异步调用
23
+
24
+ ## 🎬 快速演示
25
+ ```python
26
+ from smart_agents import SimpleAgent
27
+ from smart_agents.llm import SimpleAgentLLM
28
+ from smart_agents.tools import ToolRegistry
29
+ from smart_agents.tools.bulitin import SearchTool
30
+ # 初始化LLM
31
+ llm = SmartAgentLLM()
32
+
33
+ # 初始化工具
34
+ searchTool = SearchTool()
35
+ tool_registry.register_tool(searchTool)
36
+
37
+ # 初始化Agent
38
+ agent = SimpleAgent(
39
+ name="工具增强助手",
40
+ llm=llm,
41
+ system_prompt="你是一个智能助手,可以使用工具来帮助用户。",
42
+ tool_registry=tool_registry,
43
+ enable_tool_calling=True
44
+ )
45
+
46
+ response = agent.run("2026年小米手机最新款是什么,有什么卖点")
47
+ print(f"工具增强助手响应: {response}")
48
+ # 2026年小米手机的最新款型有几个比较主要的系列:
49
+
50
+ # 1. Redmi Note系列:主打千元长续航、耐用抗造,适合长辈、户外、备用机。
51
+ # 2. Redmi K系列:主打电竞性能、性价比旗舰,适合学生、游戏玩家。...
52
+ ```
53
+
54
+ ## 📊 架构设计
55
+ ```
56
+ ┌─────────────────────────────────────────┐
57
+ │ User Interface (API) │
58
+ └──────────────┬──────────────────────────┘
59
+
60
+ ┌──────────────▼──────────────────────────┐
61
+ │ Agent Core (ReAct) │
62
+ │ ┌────────┐ ┌────────┐ ┌──────────┐ │
63
+ │ │Planning│ │Executor│ │Reflexion │ │
64
+ │ └────────┘ └────────┘ └──────────┘ │
65
+ └──────────────┬──────────────────────────┘
66
+
67
+ ┌──────────┼──────────┐
68
+ │ │ │
69
+ ┌───▼───┐ ┌──▼───┐ ┌──▼─────┐
70
+ │Memory │ │Tools │ │LLM Prov│
71
+ │System │ │ │ │ │
72
+ └───────┘ └──────┘ └────────┘
73
+ ```
74
+
75
+ ## 🚀 快速开始
76
+
77
+ ### 安装
78
+ ```bash
79
+ # 使用pip安装
80
+ pip install smart_agents
81
+
82
+ # 或从源码安装
83
+ git clone https://github.com/edgetalker/smart_agents.git
84
+ cd hello-agents
85
+ ```
86
+
87
+ ### 配置
88
+ ```bash
89
+ cp .env.example .env
90
+ # 编辑.env文件,填入API密钥
91
+ ```
92
+
93
+ ## 📖 核心功能
94
+
95
+ ### 1️⃣ ReAct执行循环
96
+ ```python
97
+ # Agent自动进行推理-行动循环
98
+ agent.run("帮我查询AAPL股票价格并分析走势")
99
+
100
+ # 内部执行过程:
101
+ # Thought: 需要先获取股票价格
102
+ # Action: get_stock_price("AAPL")
103
+ # Observation: $178.32
104
+ # Thought: 需要分析历史数据
105
+ # Action: analyze_trend("AAPL", days=30)
106
+ # Observation: 上涨趋势...
107
+ # Final Answer: ...
108
+ ```
109
+
110
+ ### 2️⃣ 向量记忆系统
111
+ ```python
112
+ # 长期记忆存储与检索
113
+ agent.memory.store("用户偏好Python开发")
114
+ relevant = agent.memory.retrieve("编程语言")
115
+ # 自动召回相关上下文
116
+ ```
117
+
118
+ ### 3️⃣ 自定义工具
119
+ ```python
120
+ from smart_agents.tools import Tool
121
+
122
+ @Tool(
123
+ name="database_query",
124
+ description="查询MySQL数据库"
125
+ )
126
+ async def query_db(sql: str) -> str:
127
+ # 你的实现
128
+ return results
129
+ ```
130
+
131
+ ## 🗺️ 开发路线图
132
+
133
+ - [x] 基础Agent框架 (v0.1.0)
134
+ - [x] ReAct执行循环 (v0.2.0)
135
+ - [x] 向量记忆系统 (v0.3.0)
136
+ - [ ] Reflexion自我反思 (v0.4.0)
137
+ - [ ] 多Agent协作 (v0.5.0)
138
+ - [ ] 生产优化与部署 (v1.0.0)
139
+
140
+ ## 🤝 贡献
141
+
142
+ 欢迎提交Issue和Pull Request!
143
+
144
+
145
+ ## 📄 许可证
146
+
147
+ [MIT License](LICENSE) © edgetalker
148
+
149
+ ## 🙏 致谢
150
+
151
+ - DataWhale HelloAgents项目启发
152
+ - MIT 6.5940课程的优化技术
153
+ - LangChain社区的最佳实践
154
+
155
+ ## 📧 联系方式
156
+
157
+ - GitHub: [@edgetalker](https://github.com/edgetalker)
158
+ - Email: kevinpan998@gmail.com
159
+
160
+ ---
161
+
162
+ <div align="center">
163
+ 如果这个项目对你有帮助,请给个⭐️支持一下!
164
+ </div>
@@ -0,0 +1,53 @@
1
+ [build-system]
2
+ requires = ["setuptools>=61.0", "wheel"]
3
+ build-backend = "setuptools.build_meta"
4
+
5
+ [project]
6
+ name = "smartagents-py"
7
+ version = "0.1.0"
8
+ description = "A lightweight agent framework based on LLM"
9
+ readme = "README.md"
10
+ license = { file = "LICENSE" }
11
+ requires-python = ">=3.10"
12
+ authors = [
13
+ { name = "edgetalker", email = "kevinpan998@gmail.com" }
14
+ ]
15
+ keywords = ["agent", "llm", "ai", "openai"]
16
+ classifiers = [
17
+ "Programming Language :: Python :: 3",
18
+ "Programming Language :: Python :: 3.10",
19
+ "Programming Language :: Python :: 3.11",
20
+ "License :: OSI Approved :: MIT License",
21
+ "Operating System :: OS Independent",
22
+ "Topic :: Scientific/Engineering :: Artificial Intelligence",
23
+ ]
24
+
25
+ # 运行时依赖
26
+ dependencies = [
27
+ "openai>=1.0.0",
28
+ "pydantic>=2.0.0",
29
+ "requests>=2.25.0",
30
+ "python-dotenv>=1.0.0",
31
+ "tavily-python>=0.3.0",
32
+ "google-search-results>=2.4.0", # serpapi 的正确包名
33
+ ]
34
+
35
+ [project.optional-dependencies]
36
+ # 开发依赖:pip install smartagents[dev]
37
+ dev = [
38
+ "pytest>=7.0.0",
39
+ "black>=22.0.0",
40
+ ]
41
+
42
+ [project.urls]
43
+ Homepage = "https://github.com/edgetalker/smartagents"
44
+ Repository = "https://github.com/edgetalker/smartagents"
45
+ Issues = "https://github.com/edgetalker/smartagents/issues"
46
+
47
+ [tool.setuptools.packages.find]
48
+ where = ["."]
49
+ include = ["smart_agents*"]
50
+
51
+ [tool.black]
52
+ line-length = 88
53
+ target-version = ["py310"]
@@ -0,0 +1,4 @@
1
+ [egg_info]
2
+ tag_build =
3
+ tag_date = 0
4
+
@@ -0,0 +1,35 @@
1
+ """SmartAgents - A lightweight agent framework based on LLM"""
2
+
3
+ __version__ = "0.1.0"
4
+
5
+ from smart_agents.agents.simple_agent import SimpleAgent
6
+ from smart_agents.agents.react_agent import ReActAgent
7
+ from smart_agents.core.config import Config
8
+ from smart_agents.core.llm import SmartAgentLLM
9
+ from smart_agents.core.message import Message
10
+
11
+ from .tools.registry import ToolRegistry, global_registry
12
+ from .tools.builtin.search import SearchTool
13
+ from .tools.builtin.calculator import CalculatorTool
14
+ from .tools.chain import ToolChain, ToolChainManager
15
+ from .tools.async_executor import AsyncToolExecutor
16
+
17
+ __all__ = [
18
+ # 核心组件
19
+ "Config",
20
+ "SmartAgentLLM",
21
+ "Message",
22
+
23
+ # Agent 范式
24
+ "SimpleAgent",
25
+ "ReActAgent",
26
+
27
+ # 工具系统
28
+ "ToolRegistry",
29
+ "global_registry",
30
+ "SearchTool",
31
+ "CalculatorTool",
32
+ "ToolChain",
33
+ "ToolChainManager",
34
+ "AsyncToolExecutor",
35
+ ]
@@ -0,0 +1,9 @@
1
+ """Agent实现模块 - HelloAgents原生Agent范式"""
2
+
3
+ from .simple_agent import SimpleAgent
4
+ from .react_agent import ReActAgent
5
+
6
+ __all__ = [
7
+ "SimpleAgent",
8
+ "ReActAgent",
9
+ ]
@@ -0,0 +1,101 @@
1
+ from typing import Optional
2
+
3
+ from ..core.config import Config
4
+ from ..core.agent import Agent
5
+ from ..core.llm import SmartAgentLLM
6
+ from ..tools.registry import ToolRegistry
7
+ from ..core.message import Message
8
+
9
+ DEFAULT_REACT_PROMPT = """你是一个具备推理和行动能力的AI助手。你可以通过思考分析问题,然后调用合适的工具来获取信息,最终给出准确的答案。
10
+
11
+ ## 可用工具
12
+ {tools}
13
+
14
+ ## 工作流程
15
+ 请严格按照以下格式进行回应,每次只能执行一个步骤:
16
+
17
+ Thought: 分析当前问题,思考需要什么信息或采取什么行动。
18
+ Action: 选择一个行动,格式必须是以下之一:
19
+ - `{{tool_name}}[{{tool_input}}]` - 调用指定工具
20
+ - `Finish[最终答案]` - 当你有足够信息给出最终答案时
21
+
22
+ ## 重要提醒
23
+ 1. 每次回应必须包含Thought和Action两部分
24
+ 2. 工具调用的格式必须严格遵循:工具名[参数]
25
+ 3. 只有当你确信有足够信息回答问题时,才使用Finish
26
+ 4. 如果工具返回的信息不够,继续使用其他工具或相同工具的不同参数
27
+
28
+ ## 当前任务
29
+ **Question:** {question}
30
+
31
+ ## 执行历史
32
+ {history}
33
+
34
+ 现在开始你的推理和行动:
35
+ """
36
+
37
+ class ReActAgent(Agent):
38
+ """
39
+ ReAct(Reasoning and Action) Agent
40
+ 结合推理和行动的智能体
41
+ """
42
+ def __init__(
43
+ self,
44
+ name: str,
45
+ llm: SmartAgentLLM,
46
+ system_prompt: Optional[str] = None,
47
+ config: Optional[Config] = None,
48
+ tool_registry: Optional['ToolRegistry'] = None,
49
+ max_steps: int = 5,
50
+ custom_prompt: Optional[str] = None
51
+ ):
52
+ super().__init__(self, name, llm, system_prompt, config)
53
+ self.tool_registry = tool_registry
54
+ self.max_steps = max_steps
55
+ self.current_history: list[str] = []
56
+ self.prompt_template = custom_prompt if custom_prompt else DEFAULT_REACT_PROMPT
57
+
58
+ def run(self, input_text: str, **kwargs) -> str:
59
+ self.current_history = []
60
+ current_step = 0
61
+
62
+ print(f"🤖 {self.name} 开始处理问题:{input_text}")
63
+
64
+ while current_step < self.max_steps:
65
+ current_step += 1
66
+
67
+ # 获取提示词
68
+ tools_desc = self.tool_registry.get_tools_description()
69
+ history_str = "\n".join(self.current_history)
70
+ prompt = self.prompt_template.format(
71
+ tools = tools_desc,
72
+ question = input_text,
73
+ history = history_str
74
+ )
75
+
76
+ # 调用llm
77
+ messages = [{"role": "user", "content": prompt}]
78
+ response_text = self.llm.invoke(messages, **kwargs)
79
+
80
+ # 解析输出
81
+ thought, action = self._parse_output(response_text)
82
+
83
+ # 检查是否完成
84
+ if action and action.startswith('Finish'):
85
+ final_answer = self._parse_action_input(action)
86
+ self.add_message(Message(input_text, "user"))
87
+ self.add_message(Message(final_answer, "assistant"))
88
+ return final_answer
89
+
90
+ # 执行工具调用
91
+ if action:
92
+ tool_name, tool_input = self._parse_action(action)
93
+ observation = self.tool_registry.execute_tool(tool_name, tool_input)
94
+ self.current_history.append(f"Action: {action}")
95
+ self.current_history.append(f"Observation: {observation}")
96
+
97
+ # 达到最大步数
98
+ final_answer = "抱歉,我无法在限定步数内完成这个任务。"
99
+ self.add_message(Message(input_text, "user"))
100
+ self.add_message(Message(final_answer, "assistant"))
101
+ return final_answer