当前位置: 首页 > news >正文

cc/ds教学,计算机小白笔记(2.2)

代码是AI写的,用的CC接入DS-v4-pro,代码在前文基础上更新,功能包括:Agent框架,文件工具,联网搜索

本篇文章仅作为个人学习笔记记录

文件工具

完整代码如下:

""" 文件工具 Agent —— 让 AI 能读写你的文件 ======================================== 基于 04-agent-framework.py 的框架,新增两个文件工具。 展示框架的扩展能力:想加工具?写函数 → add_tool → 搞定。 """ import sys import os sys.stdout.reconfigure(encoding="utf-8") # 直接复用框架! from importlib.util import spec_from_file_location, module_from_spec spec = spec_from_file_location("framework", os.path.join(os.path.dirname(__file__), "04-agent-framework.py")) framework = module_from_spec(spec) spec.loader.exec_module(framework) Agent = framework.Agent TOOL_REGISTRY = framework.TOOL_REGISTRY.copy() # 继承基础工具 # ============================================================ # 新增工具1:读文件 # ============================================================ def read_file(path: str) -> str: """读取指定路径的文件内容""" if not os.path.exists(path): return f"文件不存在:{path}" try: with open(path, "r", encoding="utf-8") as f: content = f.read() # 限制返回长度,避免 token 爆炸 if len(content) > 3000: content = content[:3000] + "\n...(内容已截断)" return content except Exception as e: return f"读取失败:{e}" # ============================================================ # 新增工具2:写文件 # ============================================================ def write_file(path: str, content: str) -> str: """写入内容到文件。会自动创建不存在的目录。""" try: dir_path = os.path.dirname(path) if dir_path and not os.path.exists(dir_path): os.makedirs(dir_path) with open(path, "w", encoding="utf-8") as f: f.write(content) return f"文件已写入:{path}({len(content)} 个字符)" except Exception as e: return f"写入失败:{e}" # ============================================================ # 注册新工具 # ============================================================ TOOL_REGISTRY.update({ "read_file": { "func": read_file, "description": "读取电脑上的文件内容。当需要查看某个文件时使用。", "parameters": { "type": "object", "properties": { "path": {"type": "string", "description": "文件的完整路径"}, }, "required": ["path"], }, }, "write_file": { "func": write_file, "description": "将内容写入文件。用户要求保存、记录、导出时使用。", "parameters": { "type": "object", "properties": { "path": {"type": "string", "description": "要写入的文件路径"}, "content": {"type": "string", "description": "要写入的内容"}, }, "required": ["path", "content"], }, }, }) # ============================================================ # 启动 # ============================================================ if __name__ == "__main__": # 指定一个工作目录给 Agent,避免它乱翻 work_dir = os.path.join(os.path.dirname(__file__), "agent_workspace") os.makedirs(work_dir, exist_ok=True) agent = Agent(system_prompt=f"""你是一个能用工具的 AI 助手,可以用中文回答问题。 你可以: - 运行 Python 代码做计算 - 查看当前时间 - 读写电脑上的文件 文件操作的默认目录是:{work_dir} 用户说"记下来"时,你就用 write_file 保存到那个目录。 用户说"看一下"时,你就用 read_file 读取。""") for name, info in TOOL_REGISTRY.items(): agent.add_tool(name, info["func"], info["description"], info["parameters"]) print("=" * 50) print("文件 Agent —— 我能帮你读写文件了!") print(f"工作目录:{work_dir}") print("试试:") print(" '帮我写一首诗保存到 poem.txt'") print(" '帮我记一下:明天下午3点开会'") print(" '看看 poem.txt 里写了什么'") print("输入 'quit' 退出,'clear' 清空记忆") print("=" * 50) while True: user_input = input("\n你: ") if user_input.lower() == "quit": print("再见!") break if user_input.lower() == "clear": agent.clear_memory() print("(记忆已清空)") continue reply = agent.chat(user_input) print(f"AI: {reply}")

一、动态加载

普通import动态加载(当前代码)
文件必须在sys.path列出的目录中(如当前目录、PYTHONPATH)可以从任意绝对或相对路径加载,不受sys.path限制
模块名必须与文件名相同(除去.py可以任意指定模块名(如"framework"),不与文件名绑定
导入时机:在代码编写时就确定了可以在运行时决定加载哪个文件(比如根据配置)
示例:import 04_agent_framework(文件名不能以数字开头,不合法)可以加载以数字开头的文件名(如04-agent-framework.py),普通import做不到

使用普通import复用其他.py文件只需要直接import文件名(不带.py后缀)即可

1.从importlib.util导入两个辅助函数,spec_from_file_location创建一个“模块规范”ModuleSpec,描述了模块的元数据。module_from_spec根据模块规范创建一个空的模块对象。

# 直接复用框架! from importlib.util import spec_from_file_location, module_from_spec

2.spec = spec_from_file_location("framework", os.path.join(os.path.dirname(__file__), "04-agent-framework.py"))

spec_from_file_location的第一个参数"framework"是给这个模块起的名字(可以任意,不一定和文件名相同)。第二个参数是文件的完整路径,通过os.path.dirname(__file__)获取当前脚本所在的目录(__file__:当前脚本文件的路径),然后拼接上"04-agent-framework.py"。这个函数返回一个ModuleSpec对象,里面记录了“如何加载这个文件作为一个模块”。

framework = module_from_spec(spec)根据上面创建的规范,创建一个空的模块对象

spec.loader是模块对应的加载器,.exec_module(framework)是真正执行04-agent-framework.py文件中的代码,并把执行结果填充到framework这个模块对象中

spec = spec_from_file_location("framework", os.path.join(os.path.dirname(__file__), "04-agent-framework.py")) framework = module_from_spec(spec) spec.loader.exec_module(framework)

3.调用上面代码导入的framework模块,framework.Agent获取框架中的类 ,.copy()方法复制字典,避免修改原注册表

Agent = framework.Agent TOOL_REGISTRY = framework.TOOL_REGISTRY.copy() # 继承基础工具

二、文件读取

def read_file(path: str) -> str: """读取指定路径的文件内容""" if not os.path.exists(path): # 1. 检查文件是否存在 return f"文件不存在:{path}" try: with open(path, "r", encoding="utf-8") as f: # 2. 打开文件 content = f.read() # 3. 读取内容 # 4. 限制返回长度,避免 token 爆炸 if len(content) > 3000: content = content[:3000] + "\n...(内容已截断)" return content except Exception as e: # 5. 异常处理 return f"读取失败:{e}"

1.with open()是上下文管理器,自动关闭文件

as f将打开的文件对象赋值给变量f

with 表达式 [as 变量]:调用该对象的_enter_()方法,其返回值(如果有)赋值给as后面的变量。无论块内是否发生异常,都会在退出时调用上下文管理器的_exit_()方法,执行清理工作。如果_exit_返回True,则异常被压制(不再向外抛出);否则异常会继续传播。

def read_file(path: str) -> str: """读取指定路径的文件内容""" if not os.path.exists(path): # 1. 检查文件是否存在 return f"文件不存在:{path}" try: with open(path, "r", encoding="utf-8") as f: # 2. 打开文件 content = f.read() # 3. 读取内容 # 4. 限制返回长度,避免 token 爆炸 if len(content) > 3000: content = content[:3000] + "\n...(内容已截断)" return content except Exception as e: # 5. 异常处理 return f"读取失败:{e}"

2.f.read()一次性读取文件的全部内容,返回一个字符串。

content = f.read()

三、文件写入工具

1.os.makedirs()递归创建多级目录,os.makedirs(path, exist_ok=True)递归创建所有缺失目录同时在路径已存在的时候不会报错

def write_file(path: str, content: str) -> str: """写入内容到文件。会自动创建不存在的目录。""" try: dir_path = os.path.dirname(path) # 1. 获取目录路径 # 2. 如果目录不存在则创建 if dir_path and not os.path.exists(dir_path): os.makedirs(dir_path) # 递归创建目录 # 3. 写入文件 with open(path, "w", encoding="utf-8") as f: f.write(content) # 写入内容 return f"文件已写入:{path}({len(content)} 个字符)" except Exception as e: return f"写入失败:{e}"

2.if dir_path and not os.path.exists(dir_path):dir_path首先判断你给出的路径名称是不是空的,然后and not os.path.exists(dir_path):判断路径是不是已经存在了

if dir_path and not os.path.exists(dir_path):

四、工具注册

TOOL_REGISTRY.update({ "read_file": { "func": read_file, "description": "读取电脑上的文件内容。当需要查看某个文件时使用。", "parameters": { "type": "object", "properties": { "path": { "type": "string", "description": "文件的完整路径" }, }, "required": ["path"], # 必需参数 }, }, "write_file": {...} # 类似结构 })

五、主程序配置

1.创建工作目录

work_dir = os.path.join(os.path.dirname(__file__), "agent_workspace") os.makedirs(work_dir, exist_ok=True)

2.nameinfo是键值对,info也是字典,这个循环可以使主程序自动加载工具

for name, info in TOOL_REGISTRY.items(): agent.add_tool(name, info["func"], info["description"], info["parameters"])
http://www.jsqmd.com/news/892979/

相关文章:

  • alert - So
  • 南京少儿围棋考级培训推荐:南京棋院考级专长 - 19120507004
  • 一文读懂 Agent Skills:AI 智能体的 “超级技能包”
  • 想找靠谱的建站服务商?这6款高实用性工具别错过!
  • 奥迪改装维修保养较好的汽修店推荐选安迪安迪专修 - 资讯速览
  • 学Simulink——开关磁阻电机(SRM)的四象限运行与转矩脉动抑制仿真
  • 汇成广告7年数智营销全链路服务全景:资质与业务解析 - 资讯速览
  • 中小团队如何利用Taotoken实现多模型API的成本优化与统一调度
  • 2026 土工布工厂哪家批发最优惠:恒全土工材料批量特惠 - 13425704091
  • 2026 AI搜索优化白皮书:品牌信任链的重构与交付标准 - 资讯速览
  • 开源界报表扛把子:JimuReport积木报表到底是个什么产品?优势在哪,又有哪些竞品
  • 王铎行书立轴《赠静观长老方外友之二首》欣赏
  • 【深度解析】Open Human:Local-First 记忆树驱动的桌面 AI Agent 架构与实战
  • 对比直接使用官方API体验Taotoken在延迟与路由容灾方面的实际感受
  • 30亿GEO市场谁在领跑?2026年GEO优化公司综合权威实力排行榜 - GEO优化
  • 全国陪诊顾问报名条件详解,零基础、宝妈、上班族都能报名吗? - 深鉴新闻
  • 2026年苏州机械工厂GEO优化哪家好?| 行业排名新优势 - 资讯快报
  • AI大模型三种部署方式与企业落地全解析
  • 南京少儿围棋考级培训排名:南京棋院榜单领先 - 13724980961
  • Python全栈修炼之路 | 第6篇:条件判断与循环控制
  • 中山琪朗丨2026 精选推荐・实力工厂,酒店灯饰定制 + 高端定制灯饰 - 资讯速览
  • 2026年国内五大特色营销服务机构深度对比 - GEO优化
  • 数智营销服务商能力评估参考:四个维度看汇成广告的落地效果 - 资讯速览
  • ClaudeCode入门11-CLAUDE.md深度配置(小白入门:让AI真正“懂“你的项目,效率翻10倍的秘密武器)
  • KMS_VL_ALL_AIO:告别Windows和Office激活困扰的智能解决方案
  • 食品标签“文字游戏”何时休?——透视“名不副实”背后的标准与监管困局
  • AI智能体时代来了!一个让普通人也能1人运营一家公司的开源社区火了
  • 降权、预算归零、错失窗口期:2026年企业选择SEO服务商最容易踩的三个大坑 - GEO优化
  • 基于BCA特征选择与CNN-RNN混合模型的情感分析优化实践
  • 市面上的3D低代码编辑器真有黑科技?拆开底层:全是Three.js套壳!