diff --git a/functionality/calculator_assistant/README.md b/functionality/calculator_assistant/README.md new file mode 100644 index 00000000..5fef93fe --- /dev/null +++ b/functionality/calculator_assistant/README.md @@ -0,0 +1,211 @@ +# 计算器助手示例 + +## 示例介绍 + +这个示例展示了如何使用 AgentScope 创建一个**计算器助手**,它可以帮助用户进行各种数学计算,包括基本运算、复杂表达式求值和科学计算。 + +## 功能特性 + +- ✅ **基本运算**: 加法、减法、乘法、除法 +- ✅ **高级运算**: 幂运算、开方、对数等 +- ✅ **表达式求值**: 支持复杂的数学表达式 +- ✅ **结构化输出**: 使用 Pydantic 模型确保输出格式 +- ✅ **代码执行**: 使用 Python 代码确保计算准确性 + +## 快速开始 + +### 1. 环境准备 + +确保已安装 AgentScope 并设置了环境变量: + +```bash +# 设置 DashScope API Key +export DASHSCOPE_API_KEY="your_dashscope_api_key_here" + +# Windows PowerShell: +$env:DASHSCOPE_API_KEY="your_dashscope_api_key_here" +``` + +### 2. 运行示例 + +```bash +python main.py +``` + +## 使用示例 + +### 示例 1: 基本运算 + +``` +用户: 计算 123 + 456 +助手: 123 + 456 = 579 +``` + +### 示例 2: 复杂表达式 + +``` +用户: 计算 (25 * 4) / 2 + 10 +助手: +首先计算 25 * 4 = 100 +然后计算 100 / 2 = 50 +最后计算 50 + 10 = 60 +答案是 60 +``` + +### 示例 3: 科学计算 + +``` +用户: 计算 2 的 10 次方 +助手: 2^10 = 1024 +``` + +### 示例 4: 几何计算 + +``` +用户: 如果一个圆的半径是 5,求它的面积 +助手: +圆的面积公式是 π * r² +π ≈ 3.14159 +r = 5 +面积 = 3.14159 * 5² = 3.14159 * 25 ≈ 78.54 +``` + +### 示例 5: 结构化输出 + +程序启动时会自动演示结构化输出功能: + +```json +{ + "expression": "123 * 456", + "result": 56088.0, + "operation": "multiplication" +} +``` + +## 技术实现 + +### 结构化输出模型 + +使用 Pydantic 模型定义计算结果的结构: + +```python +class CalculationResult(BaseModel): + """计算结果的结构化输出模型""" + + expression: str = Field(description="数学表达式") + result: float = Field(description="计算结果") + operation: Literal["addition", "subtraction", "multiplication", + "division", "power", "other"] = Field( + description="运算类型" + ) +``` + +### 工具使用 + +助手使用 `execute_python_code` 工具来执行精确的计算: + +```python +# 当用户询问复杂计算时,助手会使用 Python 代码 +# 例如:eval("(25 * 4) / 2 + 10") +``` + +### 代码结构 + +```python +# 创建工具包 +toolkit = Toolkit() +toolkit.register_tool_function(execute_python_code) + +# 创建智能体 +calculator = ReActAgent( + name="Calculator", + sys_prompt="...", # 定义助手的计算能力 + toolkit=toolkit, + # ... 其他配置 +) + +# 使用结构化输出 +result = await calculator(query, structured_model=CalculationResult) +``` + +## 扩展功能 + +你可以根据需要扩展这个示例: + +### 1. 添加单位转换 + +```python +@tool +async def convert_units(value: float, from_unit: str, to_unit: str) -> dict: + """单位转换""" + # 实现单位转换逻辑 + pass +``` + +### 2. 添加数学函数 + +```python +@tool +async def calculate_statistics(numbers: list[float]) -> dict: + """计算统计信息""" + import statistics + return { + "mean": statistics.mean(numbers), + "median": statistics.median(numbers), + "std_dev": statistics.stdev(numbers), + } +``` + +### 3. 添加图形绘制 + +```python +@tool +async def plot_function(expression: str, x_range: tuple) -> str: + """绘制函数图像""" + import matplotlib.pyplot as plt + import numpy as np + # 实现绘图逻辑 + pass +``` + +### 4. 添加公式求解 + +```python +from sympy import symbols, solve + +@tool +async def solve_equation(equation: str) -> dict: + """求解方程""" + x = symbols('x') + solutions = solve(equation, x) + return {"solutions": [str(s) for s in solutions]} +``` + +## 应用场景 + +- 📊 **数据分析和处理**: 快速计算统计数据 +- 📐 **工程计算**: 工程项目的数学计算 +- 🎓 **学习辅助**: 帮助学生理解数学概念 +- 💼 **金融计算**: 利息、投资回报等计算 +- 🔬 **科学研究**: 科学实验的数据处理 + +## 注意事项 + +⚠️ **精度考虑**: +- 对于高精度计算,建议使用 `decimal` 模块 +- 浮点数运算可能存在精度问题 + +⚠️ **安全性**: +- 使用 `execute_python_code` 时要确保代码安全性 +- 避免执行用户提供的未经验证的代码 + +## 相关文档 + +- [结构化输出文档](https://doc.agentscope.io/tutorial/task_agent.html#structured-output) +- [工具使用文档](https://doc.agentscope.io/tutorial/task_tool.html) +- [Pydantic 文档](https://docs.pydantic.dev/) + +## 贡献 + +欢迎提交 Issue 或 Pull Request 来改进这个示例! + diff --git a/functionality/calculator_assistant/main.py b/functionality/calculator_assistant/main.py new file mode 100644 index 00000000..52744aea --- /dev/null +++ b/functionality/calculator_assistant/main.py @@ -0,0 +1,106 @@ +# -*- coding: utf-8 -*- +"""计算器助手示例 - 展示如何使用 AgentScope 创建能够进行数学计算的智能助手""" +import asyncio +import json +import os +from typing import Literal + +from pydantic import BaseModel, Field + +from agentscope.agent import ReActAgent, UserAgent +from agentscope.formatter import DashScopeChatFormatter +from agentscope.memory import InMemoryMemory +from agentscope.message import Msg +from agentscope.model import DashScopeChatModel +from agentscope.tool import Toolkit, execute_python_code + + +class CalculationResult(BaseModel): + """计算结果的结构化输出模型""" + + expression: str = Field(description="数学表达式") + result: float = Field(description="计算结果") + operation: Literal[ + "addition", + "subtraction", + "multiplication", + "division", + "power", + "other", + ] = Field( + description="运算类型", + ) + + +async def main() -> None: + """计算器助手的主入口点""" + # 创建工具包 + toolkit = Toolkit() + toolkit.register_tool_function(execute_python_code) + + # 创建计算器助手智能体 + calculator = ReActAgent( + name="Calculator", + sys_prompt=( + "You are a helpful calculator assistant. " + "You can help users with various mathematical " + "calculations including:\n" + "- Basic arithmetic (addition, subtraction, " + "multiplication, division)\n" + "- Advanced operations (powers, roots, logarithms)\n" + "- Mathematical expressions evaluation\n" + "- Unit conversions\n" + "Always show your work and explain the calculation steps. " + "For complex expressions, use Python code to ensure accuracy." + ), + model=DashScopeChatModel( + api_key=os.environ.get("DASHSCOPE_API_KEY"), + model_name="qwen-max", + enable_thinking=False, + stream=True, + ), + formatter=DashScopeChatFormatter(), + toolkit=toolkit, + memory=InMemoryMemory(), + ) + + # 创建用户代理 + user = UserAgent("User") + + print("=" * 60) + print("计算器助手已启动!") + print("你可以尝试以下操作:") + print("- 基本运算:'计算 123 + 456'") + print("- 复杂表达式:'计算 (25 * 4) / 2 + 10'") + print("- 科学计算:'计算 2 的 10 次方'") + print("- 数学问题:'如果一个圆的半径是 5,求它的面积'") + print("- 输入 'exit' 退出") + print("=" * 60) + print() + + # 演示:结构化输出 + print("演示:结构化输出计算") + print("-" * 60) + demo_query = Msg( + "user", + "计算 123 乘以 456 的结果", + "user", + ) + result = await calculator(demo_query, structured_model=CalculationResult) + if result.metadata: + print("\n结构化计算结果:") + print(json.dumps(result.metadata, indent=2, ensure_ascii=False)) + print("\n" + "=" * 60 + "\n") + + # 交互式对话循环 + msg = None + while True: + msg = await user(msg) + if msg.get_text_content().strip().lower() == "exit": + print("\n再见!") + break + msg = await calculator(msg) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/functionality/calculator_assistant/requirements.txt b/functionality/calculator_assistant/requirements.txt new file mode 100644 index 00000000..538170fd --- /dev/null +++ b/functionality/calculator_assistant/requirements.txt @@ -0,0 +1,3 @@ +agentscope[full]>=1.0.5 +pydantic>=2.0.0 + diff --git a/functionality/code_review_assistant/README.md b/functionality/code_review_assistant/README.md new file mode 100644 index 00000000..9e925c56 --- /dev/null +++ b/functionality/code_review_assistant/README.md @@ -0,0 +1,294 @@ +# 代码审查助手示例 + +## 示例介绍 + +这个示例展示了如何使用 AgentScope 创建一个**代码审查助手**,它可以帮助开发者审查代码、发现潜在问题、提供改进建议,并推荐最佳实践。 + +## 功能特性 + +- ✅ **代码分析**: 分析代码结构、逻辑和潜在问题 +- ✅ **Bug 检测**: 识别代码中的错误和潜在的 bug +- ✅ **安全审查**: 发现安全漏洞和风险 +- ✅ **性能优化**: 提供性能改进建议 +- ✅ **代码风格**: 检查代码风格和可读性 +- ✅ **最佳实践**: 推荐编程最佳实践和设计模式 + +## 快速开始 + +### 1. 环境准备 + +确保已安装 AgentScope 并设置了环境变量: + +```bash +# 设置 DashScope API Key +export DASHSCOPE_API_KEY="your_dashscope_api_key_here" + +# Windows PowerShell: +$env:DASHSCOPE_API_KEY="your_dashscope_api_key_here" +``` + +### 2. 运行示例 + +```bash +python main.py +``` + +## 使用示例 + +### 示例 1: 审查文件 + +``` +用户: 请审查 main.py 这个文件 + +助手: +[助手会读取文件内容并进行全面审查] + +审查结果: +1. **代码结构**: 整体结构清晰... +2. **潜在问题**: + - 第 15 行:变量名不够描述性 + - 第 23 行:缺少异常处理 +3. **改进建议**: ... +``` + +### 示例 2: 审查代码片段 + +``` +用户: 请审查这段代码: +def calculate_total(items): + total = 0 + for item in items: + total += item.price + return total + +助手: +代码审查结果: + +✅ **优点**: +- 函数逻辑清晰 +- 代码简洁易懂 + +⚠️ **问题**: +1. 缺少输入验证:如果 items 为 None 会报错 +2. 没有处理价格可能为负数的情况 +3. 函数缺少文档字符串 + +💡 **改进建议**: +def calculate_total(items): + """计算商品总价""" + if not items: + return 0.0 + + total = 0.0 + for item in items: + if item.price < 0: + raise ValueError(f"商品 {item.name} 价格不能为负数") + total += item.price + return total +``` + +### 示例 3: 安全审查 + +``` +用户: 这段代码有什么安全问题吗? +user_input = input("请输入用户名: ") +query = f"SELECT * FROM users WHERE username = '{user_input}'" + +助手: +🔴 **严重安全问题**: SQL 注入漏洞 + +问题分析: +- 直接将用户输入拼接到 SQL 查询中 +- 恶意用户可能输入 ' OR '1'='1 来绕过验证 + +修复建议: +使用参数化查询: +query = "SELECT * FROM users WHERE username = ?" +cursor.execute(query, (user_input,)) +``` + +### 示例 4: 性能优化 + +``` +用户: 如何优化这段代码的性能? +data = [] +for i in range(1000000): + data.append(i * 2) + +助手: +性能优化建议: + +当前代码的问题: +- 使用 append 在循环中逐步扩展列表,效率较低 + +优化方案: +1. 使用列表推导式(推荐): + data = [i * 2 for i in range(1000000)] + +2. 或使用生成器(如果不需要一次性生成所有数据): + data = (i * 2 for i in range(1000000)) + +性能提升:约 2-3 倍 +``` + +### 示例 5: 最佳实践咨询 + +``` +用户: Python 函数命名的最佳实践是什么? + +助手: +Python 函数命名最佳实践: + +1. **使用小写字母和下划线**: + ✅ 正确:calculate_total_price + ❌ 错误:CalculateTotalPrice (这是类名风格) + +2. **使用描述性名称**: + ✅ 正确:get_user_by_id + ❌ 错误:get_u + +3. **动词开头**: + ✅ 正确:process_data, validate_input + ❌ 错误:data_processor, input_validator + +4. **避免缩写**: + ✅ 正确:calculate_average + ❌ 错误:calc_avg + +更多内容请参考 PEP 8 风格指南... +``` + +## 技术实现 + +### 工具使用 + +代码审查助手使用了以下工具: + +1. **`view_text_file`**: 读取和分析代码文件 + ```python + # 助手会自动读取文件内容 + await view_text_file("path/to/file.py") + ``` + +2. **`execute_python_code`**: 测试代码逻辑 + ```python + # 可以执行代码来验证逻辑 + await execute_python_code("code_snippet") + ``` + +### 系统提示设计 + +助手使用了详细的系统提示来指导其行为: + +```python +sys_prompt = """ +You are an expert code reviewer assistant. +You help developers improve their code quality by: +- Analyzing code for bugs and potential issues +- Suggesting improvements for code readability +- Identifying security vulnerabilities +- Recommending best practices +... +""" +``` + +## 扩展功能 + +你可以根据需要扩展这个示例: + +### 1. 添加代码格式化检查 + +```python +@tool +async def check_code_format(filepath: str) -> dict: + """检查代码格式是否符合 PEP 8""" + import subprocess + result = subprocess.run( + ["flake8", filepath], + capture_output=True, + text=True, + ) + return {"issues": result.stdout.splitlines()} +``` + +### 2. 添加复杂度分析 + +```python +@tool +async def analyze_complexity(filepath: str) -> dict: + """分析代码复杂度""" + import radon.complexity as cc_mod + + with open(filepath) as f: + code = f.read() + + complexity = cc_mod.cc_visit(code) + return {"complexity": [str(c) for c in complexity]} +``` + +### 3. 添加依赖分析 + +```python +@tool +async def analyze_dependencies(filepath: str) -> dict: + """分析代码依赖""" + import ast + + with open(filepath) as f: + tree = ast.parse(f.read()) + + imports = [] + for node in ast.walk(tree): + if isinstance(node, ast.Import): + imports.extend([alias.name for alias in node.names]) + elif isinstance(node, ast.ImportFrom): + imports.append(node.module) + + return {"imports": imports} +``` + +### 4. 集成静态分析工具 + +```python +# 可以集成 pylint, mypy, bandit 等工具 +import pylint.lint + +@tool +async def run_pylint(filepath: str) -> dict: + """运行 pylint 检查""" + results = pylint.lint.Run([filepath], exit=False) + return {"score": results.linter.stats.global_note} +``` + +## 应用场景 + +- 🔍 **代码质量保证**: 在代码提交前进行审查 +- 👥 **团队协作**: 帮助团队成员提高代码质量 +- 📚 **学习辅助**: 帮助初学者理解最佳实践 +- 🔒 **安全审计**: 识别安全漏洞 +- ⚡ **性能优化**: 发现性能瓶颈 + +## 注意事项 + +⚠️ **审查准确性**: +- AI 助手的建议仅供参考,需要人工验证 +- 对于复杂逻辑,建议结合专业工具进行深度分析 + +⚠️ **上下文理解**: +- 助手可能无法完全理解整个项目的上下文 +- 建议提供相关的背景信息和代码注释 + +⚠️ **工具安全性**: +- 使用 `execute_python_code` 时要注意代码安全性 +- 避免执行恶意或未经验证的代码 + +## 相关文档 + +- [AgentScope 工具文档](https://doc.agentscope.io/tutorial/task_tool.html) +- [代码审查最佳实践](https://google.github.io/eng-practices/review/) +- [PEP 8 Python 风格指南](https://pep8.org/) + +## 贡献 + +欢迎提交 Issue 或 Pull Request 来改进这个示例! + diff --git a/functionality/code_review_assistant/main.py b/functionality/code_review_assistant/main.py new file mode 100644 index 00000000..74764234 --- /dev/null +++ b/functionality/code_review_assistant/main.py @@ -0,0 +1,79 @@ +# -*- coding: utf-8 -*- +"""代码审查助手示例 - 展示如何使用 AgentScope 创建能够审查代码的智能助手""" +import asyncio +import os + +from agentscope.agent import ReActAgent, UserAgent +from agentscope.formatter import DashScopeChatFormatter +from agentscope.memory import InMemoryMemory +from agentscope.model import DashScopeChatModel +from agentscope.tool import ( + Toolkit, + execute_python_code, + view_text_file, +) + + +async def main() -> None: + """代码审查助手的主入口点""" + # 创建工具包 + toolkit = Toolkit() + toolkit.register_tool_function(view_text_file) + toolkit.register_tool_function(execute_python_code) + + # 创建代码审查助手智能体 + reviewer = ReActAgent( + name="CodeReviewer", + sys_prompt=( + "You are an expert code reviewer assistant. " + "You help developers improve their code quality by:\n" + "- Analyzing code for bugs and potential issues\n" + "- Suggesting improvements for code readability " + "and maintainability\n" + "- Identifying security vulnerabilities\n" + "- Recommending best practices and design patterns\n" + "- Providing performance optimization suggestions\n\n" + "When reviewing code:\n" + "1. First, read and understand the code structure\n" + "2. Identify issues in categories: bugs, security, " + "performance, style\n" + "3. Provide specific, actionable feedback\n" + "4. Suggest concrete improvements with examples\n" + "5. Be constructive and professional in your feedback" + ), + model=DashScopeChatModel( + api_key=os.environ.get("DASHSCOPE_API_KEY"), + model_name="qwen-max", + enable_thinking=False, + stream=True, + ), + formatter=DashScopeChatFormatter(), + toolkit=toolkit, + memory=InMemoryMemory(), + ) + + # 创建用户代理 + user = UserAgent("User") + + print("=" * 60) + print("代码审查助手已启动!") + print("你可以尝试以下操作:") + print("- 审查文件:'请审查 main.py 这个文件'") + print("- 审查代码片段:直接粘贴代码让助手审查") + print("- 询问最佳实践:'Python 函数命名的最佳实践是什么?'") + print("- 输入 'exit' 退出") + print("=" * 60) + print() + + # 主对话循环 + msg = None + while True: + msg = await user(msg) + if msg.get_text_content().strip().lower() == "exit": + print("\n再见!") + break + msg = await reviewer(msg) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/functionality/code_review_assistant/requirements.txt b/functionality/code_review_assistant/requirements.txt new file mode 100644 index 00000000..94373e51 --- /dev/null +++ b/functionality/code_review_assistant/requirements.txt @@ -0,0 +1,2 @@ +agentscope[full]>=1.0.5 + diff --git a/functionality/file_operations_assistant/README.md b/functionality/file_operations_assistant/README.md new file mode 100644 index 00000000..6781d930 --- /dev/null +++ b/functionality/file_operations_assistant/README.md @@ -0,0 +1,168 @@ +# 文件操作助手示例 + +## 示例介绍 + +这个示例展示了如何使用 AgentScope 创建一个**文件操作助手**,它可以帮助用户执行各种文件相关的操作,如读取文件、搜索文件、创建文件等。 + +## 功能特性 + +- ✅ **文件读取**: 查看和读取文件内容 +- ✅ **文件搜索**: 在当前目录或指定目录中搜索文件 +- ✅ **文件创建**: 创建新文件并写入内容 +- ✅ **文件操作**: 使用 Python 代码或 Shell 命令进行复杂的文件操作 +- ✅ **交互式对话**: 通过自然语言与助手交互 + +## 快速开始 + +### 1. 环境准备 + +确保已安装 AgentScope 并设置了环境变量: + +```bash +# 设置 DashScope API Key +export DASHSCOPE_API_KEY="your_dashscope_api_key_here" + +# Windows PowerShell: +$env:DASHSCOPE_API_KEY="your_dashscope_api_key_here" +``` + +### 2. 运行示例 + +```bash +python main.py +``` + +## 使用示例 + +启动后,你可以通过自然语言与助手交互: + +### 示例 1: 查看文件内容 + +``` +用户: 查看 README.md 的内容 +助手: [助手会读取并显示文件内容] +``` + +### 示例 2: 搜索文件 + +``` +用户: 在当前目录搜索所有 Python 文件 +助手: [助手会使用 find 或 dir 命令搜索文件] +``` + +### 示例 3: 创建文件 + +``` +用户: 创建一个名为 notes.txt 的文件,内容是 "今日任务:学习 AgentScope" +助手: [助手会创建文件并写入指定内容] +``` + +### 示例 4: 运行 Shell 命令 + +``` +用户: 列出当前目录的所有文件 +助手: [助手会执行 ls 或 dir 命令] +``` + +### 示例 5: 使用 Python 进行复杂操作 + +``` +用户: 统计当前目录下所有 .py 文件的行数 +助手: [助手会编写 Python 代码来完成这个任务] +``` + +## 技术实现 + +### 工具集成 + +本示例使用了以下 AgentScope 内置工具: + +1. **`execute_shell_command`**: 执行 Shell 命令 + - Windows: `dir`, `cd`, `type` 等 + - Linux/Mac: `ls`, `grep`, `find` 等 + +2. **`execute_python_code`**: 执行 Python 代码 + - 可以进行复杂的文件处理 + - 支持文件 I/O、JSON 处理等 + +3. **`view_text_file`**: 查看文本文件内容 + - 安全地读取文件内容 + - 支持大文件的分页查看 + +### 代码结构 + +```python +# 创建工具包 +toolkit = Toolkit() +toolkit.register_tool_function(execute_shell_command) +toolkit.register_tool_function(execute_python_code) +toolkit.register_tool_function(view_text_file) + +# 创建智能体 +assistant = ReActAgent( + name="FileAssistant", + sys_prompt="...", # 定义助手的职责和能力 + toolkit=toolkit, # 注册工具 + # ... 其他配置 +) +``` + +## 扩展功能 + +你可以根据需要扩展这个示例: + +### 1. 添加自定义文件工具 + +```python +from agentscope.tool import tool + +@tool +async def count_file_lines(filepath: str) -> dict: + """统计文件行数""" + with open(filepath, 'r', encoding='utf-8') as f: + lines = len(f.readlines()) + return {"file": filepath, "lines": lines} + +# 注册自定义工具 +toolkit.register_tool_function(count_file_lines) +``` + +### 2. 添加文件类型识别 + +```python +@tool +async def detect_file_type(filepath: str) -> dict: + """检测文件类型""" + import mimetypes + mime_type, _ = mimetypes.guess_type(filepath) + return {"file": filepath, "type": mime_type} +``` + +### 3. 集成更多文件操作 + +- 文件压缩/解压 +- 批量重命名 +- 文件权限管理 +- 文件同步 + +## 注意事项 + +⚠️ **安全提示**: +- 助手可以执行文件操作,请谨慎使用 +- 建议在测试环境中运行 +- 避免授予过高权限 + +⚠️ **平台差异**: +- Shell 命令在 Windows 和 Linux/Mac 上有所不同 +- 助手会根据操作系统自动选择合适的命令 + +## 相关文档 + +- [AgentScope 工具文档](https://doc.agentscope.io/tutorial/task_tool.html) +- [ReAct Agent 文档](https://doc.agentscope.io/tutorial/task_agent.html) +- [内置工具列表](https://doc.agentscope.io/api/agentscope.tool.html) + +## 贡献 + +欢迎提交 Issue 或 Pull Request 来改进这个示例! + diff --git a/functionality/file_operations_assistant/main.py b/functionality/file_operations_assistant/main.py new file mode 100644 index 00000000..92e8354a --- /dev/null +++ b/functionality/file_operations_assistant/main.py @@ -0,0 +1,78 @@ +# -*- coding: utf-8 -*- +"""文件操作助手示例 - 展示如何使用 AgentScope 创建一个能够进行文件操作的智能助手""" +import asyncio +import os + +from agentscope.agent import ReActAgent, UserAgent +from agentscope.formatter import DashScopeChatFormatter +from agentscope.memory import InMemoryMemory +from agentscope.model import DashScopeChatModel +from agentscope.tool import ( + Toolkit, + execute_python_code, + execute_shell_command, + view_text_file, +) + + +async def main() -> None: + """文件操作助手的主入口点""" + # 创建工具包并注册文件相关工具 + toolkit = Toolkit() + + # 注册工具函数 + toolkit.register_tool_function(execute_shell_command) + toolkit.register_tool_function(execute_python_code) + toolkit.register_tool_function(view_text_file) + + # 创建文件操作助手智能体 + assistant = ReActAgent( + name="FileAssistant", + sys_prompt=( + "You are a helpful file operations assistant. " + "You can help users with various file operations including:\n" + "- Reading and viewing file contents\n" + "- Searching for files and text within files\n" + "- Creating, modifying, and deleting files\n" + "- Organizing files and directories\n" + "Always provide clear explanations of what you're doing. " + "Be careful with file operations that might modify or " + "delete files." + ), + model=DashScopeChatModel( + api_key=os.environ.get("DASHSCOPE_API_KEY"), + model_name="qwen-max", + enable_thinking=False, + stream=True, + ), + formatter=DashScopeChatFormatter(), + toolkit=toolkit, + memory=InMemoryMemory(), + ) + + # 创建用户代理 + user = UserAgent("User") + + print("=" * 60) + print("文件操作助手已启动!") + print("你可以尝试以下操作:") + print("- 查看文件内容:'查看 README.md 的内容'") + print("- 搜索文件:'在当前目录搜索 Python 文件'") + print("- 创建文件:'创建一个名为 test.txt 的文件,内容是 Hello World'") + print("- 运行命令:'列出当前目录的所有文件'") + print("- 输入 'exit' 退出") + print("=" * 60) + print() + + # 主对话循环 + msg = None + while True: + msg = await user(msg) + if msg.get_text_content().strip().lower() == "exit": + print("\n再见!") + break + msg = await assistant(msg) + + +if __name__ == "__main__": + asyncio.run(main()) diff --git a/functionality/file_operations_assistant/requirements.txt b/functionality/file_operations_assistant/requirements.txt new file mode 100644 index 00000000..94373e51 --- /dev/null +++ b/functionality/file_operations_assistant/requirements.txt @@ -0,0 +1,2 @@ +agentscope[full]>=1.0.5 +