tools_complete_demo.py 4.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188
  1. """
  2. 完整工具系统使用示例
  3. 演示基础工具和高级工具的使用。
  4. """
  5. import asyncio
  6. from agent.tools.builtin import (
  7. read_file,
  8. edit_file,
  9. write_file,
  10. bash_command,
  11. glob_files,
  12. grep_content
  13. )
  14. async def demo_basic_tools():
  15. """演示基础工具(Python 实现)"""
  16. print("=" * 60)
  17. print("基础工具演示")
  18. print("=" * 60)
  19. # 1. 读取文件
  20. print("\n1. 读取文件")
  21. result = await read_file(file_path="README.md", limit=20)
  22. print(f"✅ {result.title}")
  23. print(f" 前 5 行: {result.output[:200]}...")
  24. # 2. 搜索文件
  25. print("\n2. Glob 搜索")
  26. result = await glob_files(pattern="**/*.py", path="agent/tools")
  27. print(f"✅ {result.title}")
  28. print(f" 找到 {result.metadata['count']} 个文件")
  29. # 3. 内容搜索
  30. print("\n3. Grep 搜索")
  31. result = await grep_content(
  32. pattern="async def",
  33. path="agent/tools/builtin",
  34. include="*.py"
  35. )
  36. print(f"✅ {result.title}")
  37. print(f" 找到 {result.metadata['matches']} 个匹配")
  38. # 4. 执行命令
  39. print("\n4. Bash 命令")
  40. result = await bash_command(
  41. command="git status --short",
  42. timeout=10
  43. )
  44. print(f"✅ {result.title}")
  45. print(f" 退出码: {result.metadata['exit_code']}")
  46. # 5. 编辑文件(演示智能匹配)
  47. print("\n5. 智能编辑(9 种策略)")
  48. # 创建测试文件
  49. test_content = """
  50. def hello():
  51. print("Hello")
  52. def world():
  53. print("World")
  54. """
  55. await write_file(file_path="/tmp/test_edit.py", content=test_content)
  56. # 编辑:忽略缩进(会使用 IndentationFlexibleReplacer)
  57. result = await edit_file(
  58. file_path="/tmp/test_edit.py",
  59. old_string='def hello():\nprint("Hello")', # 缩进不同
  60. new_string='def hello():\n print("Hello, World!")'
  61. )
  62. print(f"✅ {result.title}")
  63. print(f" Diff:\n{result.metadata['diff'][:200]}...")
  64. async def demo_advanced_tools():
  65. """演示高级工具(Bun 适配器)"""
  66. print("\n" + "=" * 60)
  67. print("高级工具演示(需要 Bun)")
  68. print("=" * 60)
  69. try:
  70. from agent.tools.advanced import webfetch, lsp_diagnostics
  71. # 1. 网页抓取
  72. print("\n1. 网页抓取 (HTML -> Markdown)")
  73. result = await webfetch(
  74. url="https://example.com",
  75. format="markdown"
  76. )
  77. print(f"✅ {result.title}")
  78. print(f" 内容长度: {len(result.output)} 字符")
  79. # 2. LSP 诊断
  80. print("\n2. LSP 诊断")
  81. result = await lsp_diagnostics(
  82. file_path="agent/tools/builtin/edit.py"
  83. )
  84. print(f"✅ {result.title}")
  85. print(f" 诊断结果: {result.output[:200]}...")
  86. except Exception as e:
  87. print(f"⚠️ 高级工具需要 Bun 运行时: {e}")
  88. print(" 安装: curl -fsSL https://bun.sh/install | bash")
  89. async def demo_edit_strategies():
  90. """演示 edit_file 的 9 种匹配策略"""
  91. print("\n" + "=" * 60)
  92. print("edit_file 策略演示")
  93. print("=" * 60)
  94. test_cases = [
  95. {
  96. "name": "策略 1: 精确匹配",
  97. "content": "DEBUG = True\nVERBOSE = False",
  98. "old": "DEBUG = True",
  99. "new": "DEBUG = False"
  100. },
  101. {
  102. "name": "策略 2: 忽略行首尾空白",
  103. "content": " DEBUG = True \nVERBOSE = False",
  104. "old": "DEBUG = True", # 无空白
  105. "new": "DEBUG = False"
  106. },
  107. {
  108. "name": "策略 4: 空白归一化",
  109. "content": "DEBUG = True",
  110. "old": "DEBUG = True", # 单空格
  111. "new": "DEBUG = False"
  112. },
  113. {
  114. "name": "策略 5: 灵活缩进",
  115. "content": """
  116. def foo():
  117. if True:
  118. print("hello")
  119. """,
  120. "old": "if True:\nprint(\"hello\")", # 无缩进
  121. "new": "if True:\n print(\"world\")"
  122. }
  123. ]
  124. for i, test in enumerate(test_cases, 1):
  125. print(f"\n{i}. {test['name']}")
  126. # 创建测试文件
  127. test_file = f"/tmp/test_strategy_{i}.py"
  128. await write_file(file_path=test_file, content=test["content"])
  129. # 执行编辑
  130. try:
  131. result = await edit_file(
  132. file_path=test_file,
  133. old_string=test["old"],
  134. new_string=test["new"]
  135. )
  136. print(f" ✅ 成功匹配")
  137. except Exception as e:
  138. print(f" ❌ 失败: {e}")
  139. async def main():
  140. """运行所有演示"""
  141. print("\n🚀 工具系统完整演示\n")
  142. # 基础工具
  143. await demo_basic_tools()
  144. # 编辑策略
  145. await demo_edit_strategies()
  146. # 高级工具
  147. await demo_advanced_tools()
  148. print("\n" + "=" * 60)
  149. print("演示完成!")
  150. print("=" * 60)
  151. if __name__ == "__main__":
  152. asyncio.run(main())