当前位置:首页>python>AI Agent小demo-python版本

AI Agent小demo-python版本

  • 2026-06-29 20:38:31
AI Agent小demo-python版本
各位看官老爷五一好。不知道玩嗨了没。
文章底部附出去玩图片一张!享受假期!
一:声明
本文仅供学习,欢迎大家讨论,共同进步。
二:背景

在深入代码之前,让我们先建立一个清晰的认知,可以把 AI Agent 想象成一个拥有大脑和手脚的智能程序

  • 大脑(核心):一个能够理解、推理和决策的模型(比如大型语言模型 LLM)。它负责处理信息,制定计划。
  • 感知(输入):Agent 通过感官获取外部信息,如用户的指令、数据库查询结果、网页内容、传感器数据等。
  • 行动(输出):Agent 通过手脚影响外部世界,例如调用一个函数、发送一封邮件、在屏幕上输出文本、控制机械臂等。
  • 目标:Agent 的一切行为都围绕着一个明确的目标展开,比如:帮我查一下北京明天的天气。
在这个基础上,我们在设计demo的时候,第一个要求就是,逻辑架构必须完善,并且方便后续扩展。
直接看代码结构:
其中:agent.py负责主要实现,tools.py我们需要封装各种工具,memory.py集成上下文记忆。brain.py负责集成大模型。
如果要细分还有鉴权,校验等我们暂时不展开。
三:brain.py 智能大脑模块
Agent 的大脑需要推理能力。我们将使用 deepseek(通过 API 调用)作为我们 Agent 的大脑。
主要是因为便宜。
先安装必要的库和测试单例
#pip3 install openaiimport osfrom openai import OpenAIDEEPSEEK_API_KEY = "sk-xxxxxxx"  # 这里设置你申请的 keyDEEPSEEK_API_URL = "https://api.deepseek.com/v1"client = OpenAI(    api_key = DEEPSEEK_API_KEY,    base_url = DEEPSEEK_API_URL)response = client.chat.completions.create(    model="deepseek-v4-flash",    messages=[        {"role""system""content""You are a helpful assistant"},        {"role""user""content""Hello"},    ],    stream=False)print(response.choices[0].message.content)
然后运行成功后,请大家按照下面的格式,测试自己的brain.py
# brain.pyfrom openai import OpenAIimport osDEEPSEEK_API_KEY = "sk-xxxxxxx"  # 这里设置你申请的 keyDEEPSEEK_API_URL = "https://api.deepseek.com/v1"client = OpenAI(    api_key = DEEPSEEK_API_KEY,    base_url = DEEPSEEK_API_URL)class AgentBrain:    """Agent 的大脑,负责思考与决策"""    def __init__(self, model="deepseek-v4-flash"):        self.model = model    def think(self, prompt):        """核心思考函数:接收提示,返回模型的思考结果"""        try:            # 使用客户端调用 Chat Completions API(v1.x 版本写法)            response = client.chat.completions.create(                model=self.model,                messages=[{"role""user""content": prompt}],                temperature=0.5,  # 控制创造性,越低越专注                max_tokens=500    # 控制回复长度            )            # 提取模型返回的文本内容(v1.x 版本属性路径变更)            reasoning = response.choices[0].message.content            return reasoning.strip()        except Exception as e:            return f"思考过程出错: {e}"# 简单测试一下大脑是否工作if __name__ == "__main__":    brain = AgentBrain()    test_prompt = "你好,请简单介绍一下你自己。"    print("测试提问:", test_prompt)    print("大脑回复:", brain.think(test_prompt))
运行结果如下:
再次重申,本文用的是deepseek-v4-flash,因为便宜,你可以平替为自己喜欢的模型基座。

代码解析

  1. 我们创建了一个 AgentBrain 类来封装与 LLM 的交互。
  2. think方法是核心,它接收一个字符串 prompt(提示词),将其发送给 GPT API。
  3. temperature参数很重要:设置为 0.5 能让 Agent 在创造性和稳定性之间取得平衡,适合做规划任务。
  4. 最后返回模型生成的文本,这就是 Agent 思考的结果。
四:工具类的设计与实现
本文介绍的tools适用于日常办公场景的实用工具集合,包括文件处理、数据转换、时间管理、邮件提醒等功能。
你可以改成自己喜欢的。
代码如下:
"""tools.py - 办公自动化工具集适用于日常办公场景的实用工具集合,包括文件处理、数据转换、时间管理、邮件提醒等功能"""import datetimeimport jsonimport csvimport osimport reimport randomimport shutilfrom pathlib import Pathfrom typing import ListDictAnyOptionalUnionfrom collections import Counterimport hashlibclass OfficeTools:    """面向办公室场景的Agent工具集合"""    # ==================== 文件处理工具 ====================    @staticmethod    def read_file(file_path: str, encoding: str = 'utf-8') -> str:        """        读取文件内容(支持txt、json、csv等格式)        参数:            file_path: 文件路径            encoding: 文件编码,默认utf-8        返回:            文件内容字符串        """        try:            path = Path(file_path)            if not path.exists():                return f"[错误] 文件不存在: {file_path}"            # 根据扩展名选择读取方式            suffix = path.suffix.lower()            if suffix == '.json':                with open(path, 'r', encoding=encoding) as f:                    data = json.load(f)                return f"[JSON文件] 内容:\n{json.dumps(data, ensure_ascii=False, indent=2)}"            elif suffix == '.csv':                with open(path, 'r', encoding=encoding) as f:                    reader = csv.reader(f)                    rows = list(reader)                    if not rows:                        return "[CSV文件] 文件为空"                    # 格式化输出                    result = f"[CSV文件] 共{len(rows)}行,{len(rows[0])}列\n"                    for i, row in enumerate(rows[:20]):  # 最多显示20行                        result += f"第{i+1}行: {', '.join(row)}\n"                    if len(rows) > 20:                        result += f"... 还有{len(rows)-20}行未显示"                    return result            else:  # txt或其他文本文件                content = path.read_text(encoding=encoding)                preview = content[:1000if len(content) > 1000 else content                return f"[文本文件] 文件大小: {len(content)}字符\n预览:\n{preview}"        except Exception as e:            return f"[错误] 读取文件失败: {str(e)}"    @staticmethod    def write_file(file_path: str, content: str, mode: str = 'w') -> str:        """        写入文件内容(办公常用:写报告、保存数据等)        参数:            file_path: 文件路径            content: 要写入的内容            mode: 'w'覆盖写入,'a'追加写入        返回:            操作结果        """        try:            path = Path(file_path)            # 确保目录存在            path.parent.mkdir(parents=True, exist_ok=True)            with open(path, 'w' if mode == 'w' else 'a', encoding='utf-8'as f:                f.write(content)            return f"[成功] 内容已保存到: {file_path} (模式: {'覆盖'if mode == 'w'else'追加'})"        except Exception as e:            return f"[错误] 写入文件失败: {str(e)}"    @staticmethod    def copy_file(source: str, destination: str) -> str:        """        复制文件或文件夹        参数:            source: 源路径            destination: 目标路径        返回:            操作结果        """        try:            src = Path(source)            dst = Path(destination)            if src.is_file():                shutil.copy2(src, dst)                return f"[成功] 文件已复制: {source} -> {destination}"            elif src.is_dir():                shutil.copytree(src, dst)                return f"[成功] 文件夹已复制: {source} -> {destination}"            else:                return f"[错误] 源路径不存在: {source}"        except Exception as e:            return f"[错误] 复制失败: {str(e)}"    @staticmethod    def list_directory(path: str = '.', pattern: str = '*') -> str:        """        列出目录中的文件(办公常用:查看工作文件夹)        参数:            path: 目录路径,默认为当前目录            pattern: 文件名匹配模式,如 '*.xlsx'        返回:            文件列表        """        try:            dir_path = Path(path)            if not dir_path.exists():                return f"[错误] 目录不存在: {path}"            files = list(dir_path.glob(pattern))            # 统计文件类型            file_types = Counter(f.suffix for f in files if f.is_file())            result = f"[目录列表] {dir_path.absolute()}\n"            result += f"总计: {len(files)}个项目\n"            result += f"文件类型分布: {dict(file_types)}\n\n"            # 按修改时间排序            files.sort(key=lambda x: x.stat().st_mtime, reverse=True)            for item in files[:30]:  # 最多显示30个                if item.is_file():                    size = item.stat().st_size                    size_str = f"{size}B" if size < 1024 else f"{size/1024:.1f}KB"                    mtime = datetime.datetime.fromtimestamp(item.stat().st_mtime).strftime('%Y-%m-%d %H:%M')                    result += f"📄 {item.name} ({size_str}) - {mtime}\n"                else:                    result += f"📁 {item.name}/\n"            if len(files) > 30:                result += f"... 还有{len(files)-30}个项目未显示"            return result        except Exception as e:            return f"[错误] 列出目录失败: {str(e)}"    # ==================== 数据处理工具 ====================    @staticmethod    def parse_table_data(data: str, format_type: str = 'auto') -> str:        """        解析表格数据(CSV、Markdown表格、Excel复制文本等)        参数:            data: 原始数据字符串            format_type: 格式类型(auto/csv/md/tsv)        返回:            格式化的表格数据        """        try:            lines = data.strip().split('\n')            # 自动检测格式            if format_type == 'auto':                if '|' in lines[0and '---' in lines[1]:                    format_type = 'md'  # Markdown表格                elif '\t' in lines[0]:                    format_type = 'tsv'                elif ',' in lines[0]:                    format_type = 'csv'                else:                    return "[错误] 无法自动识别数据格式"            # 解析数据            rows = []            if format_type == 'csv':                for line in lines:                    rows.append([cell.strip() for cell in line.split(',')])            elif format_type == 'tsv':                for line in lines:                    rows.append([cell.strip() for cell in line.split('\t')])            elif format_type == 'md':                # 跳过Markdown表头分隔线                for i, line in enumerate(lines):                    if '---' in line:                        continue                    if '|' in line:                        cells = [c.strip() for c in line.split('|')[1:-1]]                        rows.append(cells)            if not rows:                return "[错误] 未找到有效数据"            # 对齐输出            col_widths = [max(len(str(row[i])) for row in rows) for i in range(len(rows[0]))]            result = f"[表格数据] {len(rows)}行 × {len(rows[0])}列\n"            # 添加表头(第一行加粗标识)            for i, row in enumerate(rows):                if i == 0:                    result += "📊 "                else:                    result += "   "                formatted = [f"{cell:<{col_widths[j]}}" for j, cell in enumerate(row)]                result += " | ".join(formatted)                if i == 0:                    result += "\n" + "   " + "-" * (sum(col_widths) + len(col_widths) * 3)                result += "\n"            return result        except Exception as e:            return f"[错误] 解析表格数据失败: {str(e)}"    @staticmethod    def convert_units(value: float, from_unit: str, to_unit: str) -> str:        """        单位转换(长度、重量、温度等)        参数:            value: 数值            from_unit: 原单位(如 'km', 'kg', 'c')            to_unit: 目标单位        返回:            转换结果        """        # 定义转换率(基准单位都用国际标准)        conversions = {            # 长度 (基准: 米)            'length': {'m'1'km'1000'cm'0.01'mm'0.001                      'in'0.0254'ft'0.3048'yd'0.9144'mile'1609.34},            # 重量 (基准: 千克)            'weight': {'kg'1'g'0.001'mg'0.000001'lb'0.453592,                      'oz'0.0283495't'1000},            # 温度 (特例)            'temperature': ['c''f''k']        }        try:            from_unit = from_unit.lower()            to_unit = to_unit.lower()            # 温度转换(特例)            if from_unit in conversions['temperature'and to_unit in conversions['temperature']:                if from_unit == 'c' and to_unit == 'f':                    result = value * 9/5 + 32                elif from_unit == 'f' and to_unit == 'c':                    result = (value - 32) * 5/9                elif from_unit == 'c' and to_unit == 'k':                    result = value + 273.15                elif from_unit == 'k' and to_unit == 'c':                    result = value - 273.15                else:                    result = value                return f"[单位转换] {value}{from_unit.upper()} = {result:.2f}{to_unit.upper()}"            # 查找单位类型            unit_type = None            for utype, units in conversions.items():                if utype != 'temperature' and from_unit in units and to_unit in units:                    unit_type = utype                    break            if not unit_type:                return f"[错误] 不支持的转换: {from_unit} -> {to_unit}"            units = conversions[unit_type]            # 转换为基准单位,再转换为目标单位            base_value = value * units[from_unit]            result = base_value / units[to_unit]            return f"[单位转换] {value}{from_unit} = {result:.4f}{to_unit}"        except Exception as e:            return f"[错误] 转换失败: {str(e)}"    # ==================== 时间管理工具 ====================    @staticmethod    def get_current_time(timezone: str = 'local') -> str:        """        获取当前时间(支持时区)        参数:            timezone: 时区(local/UTC/asia/shanghai/us/ny等)        返回:            格式化的时间信息        """        now = datetime.datetime.now()        time_info = f"[当前时间] {now.strftime('%Y年%m月%d日 %H:%M:%S')}\n"        time_info += f"📅 星期: {['一','二','三','四','五','六','日'][now.weekday()]}\n"        time_info += f"📆 第{now.strftime('%W')}周 | 本年第{now.timetuple().tm_yday}天\n"        # 添加时间戳        timestamp = int(now.timestamp())        time_info += f"⏰ 时间戳: {timestamp}\n"        # 常见时区参考        time_info += "🌍 国际时间参考:\n"        utc_now = datetime.datetime.utcnow()        time_info += f"   UTC时间: {utc_now.strftime('%H:%M')}\n"        time_info += f"   东京时间: {(now + datetime.timedelta(hours=1)).strftime('%H:%M')}\n"        time_info += f"   纽约时间: {(now - datetime.timedelta(hours=13)).strftime('%H:%M')}\n"        return time_info    @staticmethod    def calculate_workdays(start_date: str, end_date: str, include_weekend: bool = False) -> str:        """        计算工作日天数(排除周末和节假日)        参数:            start_date: 开始日期 'YYYY-MM-DD'            end_date: 结束日期 'YYYY-MM-DD'            include_weekend: 是否包含周末        返回:            工作日统计信息        """        try:            start = datetime.datetime.strptime(start_date, '%Y-%m-%d')            end = datetime.datetime.strptime(end_date, '%Y-%m-%d')            total_days = (end - start).days + 1            workdays = 0            holidays = 0            for i in range(total_days):                current = start + datetime.timedelta(days=i)                is_weekend = current.weekday() >= 5                if include_weekend:                    workdays += 1                else:                    if not is_weekend:                        workdays += 1                    else:                        holidays += 1            result = f"[工作日统计] {start_date} 至 {end_date}\n"            result += f"📊 总天数: {total_days}天\n"            result += f"💼 工作日: {workdays}天\n"            result += f"🎉 周末: {holidays}天\n"            # 简单的工作日提醒            if total_days > 30:                result += f"📌 预计需要{workdays//22}个月完成项目\n"            return result        except Exception as e:            return f"[错误] 日期格式错误,请使用 YYYY-MM-DD 格式: {str(e)}"    @staticmethod    def create_schedule(tasks: List[Dict[strAny]]) -> str:        """        创建智能日程安排        参数:            tasks: 任务列表,每个任务包含名称、预计时长(小时)、截止日期等信息                   示例: [{'name': '写报告', 'duration': 2, 'deadline': '2024-01-15', 'priority': 'high'}]        返回:            优化后的日程安排        """        if not tasks:            return "[错误] 任务列表为空"        # 优先级映射        priority_order = {'high'3'medium'2'low'1}        # 按优先级和截止日期排序        sorted_tasks = sorted(tasks,                             key=lambda x: (-priority_order.get(x.get('priority''medium'), 2),                                         x.get('deadline''9999-12-31')))        schedule = "[智能日程安排]\n"        schedule += "=" * 50 + "\n"        total_hours = 0        current_hour = 9  # 从上午9点开始        for task in sorted_tasks:            name = task.get('name''未命名任务')            duration = task.get('duration'1)            deadline = task.get('deadline''无截止日期')            priority = task.get('priority''medium')            # 优先级标志            priority_flag = {'high''🔴''medium''🟡''low''🟢'}.get(priority, '⚪')            # 计算时间段            end_hour = current_hour + duration            time_slot = f"{current_hour:02d}:00 - {end_hour:02d}:00"            schedule += f"{priority_flag}{time_slot}  |  {name}\n"            schedule += f"      ⏱️ 预计{duration}小时  |  📅 截止: {deadline}\n\n"            current_hour = end_hour            total_hours += duration            # 中午休息            if current_hour >= 12 and current_hour < 13:                schedule += "🍽️ 12:00 - 13:00 午休时间\n\n"                current_hour = 13        schedule += "=" * 50 + "\n"        schedule += f"📈 统计: 共{len(tasks)}个任务,总耗时{total_hours}小时\n"        # 工作量评估        if total_hours > 8:            schedule += "⚠️ 警告: 工作量超过8小时,建议调整优先级或分配给其他人\n"        elif total_hours < 4:            schedule += "✅ 工作量适中,可以安排一些临时任务\n"        return schedule    # ==================== 沟通协作工具 ====================    @staticmethod    def format_email(subject: str, recipient: str, body: str, sender: str = None) -> str:        """        格式化邮件内容(符合办公规范)        参数:            subject: 邮件主题            recipient: 收件人            body: 正文内容            sender: 发件人(可选)        返回:            格式化的邮件文本        """        date_str = datetime.datetime.now().strftime('%Y年%m月%d日')        email = f"""{'='*60}邮件主题: {subject}收件人: {recipient}{'发件人: ' + sender if sender else''}日期: {date_str}{'='*60}{body}{'='*60}发件时间: {datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S')}请及时查收并回复确认。"""        return email.strip()    @staticmethod    def generate_meeting_agenda(topic: str, duration: int, participants: List[str], items: List[str]) -> str:        """        生成会议议程        参数:            topic: 会议主题            duration: 会议时长(分钟)            participants: 参会人员列表            items: 议程事项列表        返回:            标准格式的会议议程        """        agenda = f"""━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━                   会议议程━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━会议主题: {topic}会议时长: {duration}分钟参会人员: {', '.join(participants)}日期: {datetime.datetime.now().strftime('%Y-%m-%d')}议程安排:"""        # 计算每个议程的时间分配        time_per_item = duration // len(items) if items else duration        for i, item in enumerate(items, 1):            agenda += f"\n{i}{item} (约{time_per_item}分钟)"        agenda += f"""注意事项:• 请准时参会• 提前准备相关资料• 重要事项请提前10分钟测试设备预计结束时间: {(datetime.datetime.now() + datetime.timedelta(minutes=duration)).strftime('%H:%M')}━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━"""        return agenda    # ==================== 搜索和计算工具 ====================    @staticmethod    def smart_search(keyword: str, search_type: str = 'all') -> str:        """        智能搜索(集成多种办公搜索需求)        参数:            keyword: 搜索关键词            search_type: 搜索类型(all/天气/新闻/代码/翻译)        返回:            搜索结果        """        # 模拟数据(实际可以接入API)        mock_data = {            '天气': {                '北京''🌤️ 晴, 15-25°C, 空气质量良, 紫外线中等',                '上海''🌧️ 小雨, 18-22°C, 湿度85%, 带伞出行',                '深圳''☀️ 晴朗, 22-28°C, 适合户外活动'            },            '新闻': {                '科技''AI技术日新月异,办公自动化成为趋势...',                '经济''数字化转型加速,远程办公常态化...'            },            '文档': {                '合同模板''【合同模板】劳动合同_标准版_v2.3.docx',                '周报模板''【周报模板】工作周报_简洁版.xlsx',                'PPT模板''【PPT模板】年终总结_商务风.pptx'            }        }        result = f"[智能搜索] 关键词: '{keyword}'\n\n"        # 搜索类型处理        if search_type == '天气' or keyword in ['天气''气温']:            result += "🌤️ 天气信息:\n"            for city, weather in mock_data['天气'].items():                result += f"  {city}{weather}\n"        elif search_type == '文档' or keyword in ['模板''文档']:            result += "📄 办公文档模板:\n"            for name, desc in mock_data['文档'].items():                result += f"  • {name}{desc}\n"        elif search_type == '代码':            result += "💻 常用代码片段:\n"            result += "  • Python读取Excel: pd.read_excel('file.xlsx')\n"            result += "  • 发送邮件: smtplib.SMTP()\n"            result += "  • 文件处理: pathlib.Path()\n"        else:            result += "📋 推荐相关资源:\n"            for category in ['文档''代码''常用链接']:                result += f"  • {category}: 可进一步细化搜索\n"        result += "\n💡 提示: 可以使用更精确的关键词获得更好结果"        return result    @staticmethod    def calculate_safe(expression: str) -> str:        """        安全计算器(支持办公常用计算)        参数:            expression: 数学表达式,如 '3*5+2', '总价/数量', '10% of 200'        返回:            计算结果        """        try:            # 处理百分比的特殊情况            if '%' in expression and 'of' in expression:                # 解析 'X% of Y'                import re                match = re.search(r'(\d+(?:\.\d+)?)%\s+of\s+(\d+(?:\.\d+)?)', expression)                if match:                    percent = float(match.group(1))                    total = float(match.group(2))                    result = (percent / 100) * total                    return f"[计算器] {expression} = {result:.2f}"            # 允许的字符:数字、运算符、括号、小数点、空格            allowed_chars = set("0123456789+-*/().% ")            if not all(c in allowed_chars for c in expression):                return "[计算器] 表达式包含非法字符,拒绝计算"            # 替换%为/100            clean_expr = expression.replace('%''/100')            clean_expr = clean_expr.replace(' ''')            # 安全执行计算            safe_globals = {'__builtins__': {}, 'pow'pow'abs'abs}            result = eval(clean_expr, safe_globals)            # 格式化结果(处理浮点数)            if isinstance(result, float):                if result.is_integer():                    result = int(result)                else:                    result = round(result, 4)            return f"[计算器] {expression} = {result}"        except ZeroDivisionError:            return "[计算器] 错误:除数不能为零"        except SyntaxError:            return "[计算器] 错误:表达式语法有误(括号不匹配或运算符错误)"        except Exception as e:            return f"[计算器] 计算错误: {str(e)}"    # ==================== 快捷工具 ====================    @staticmethod    def text_to_markdown(text: str, style: str = 'basic') -> str:        """        文本转Markdown格式(办公写作)        参数:            text: 原始文本            style: 样式(basic/文章/列表)        返回:            Markdown格式文本        """        lines = text.strip().split('\n')        if style == 'basic':            # 自动识别标题(行首有数字+点的)            result = []            for line in lines:                if re.match(r'^\d+\.', line):                    result.append(f"### {line}")                elif line.strip() and not line.startswith('#'):                    result.append(line)                else:                    result.append(line)            return '\n\n'.join(result)        elif style == '文章':            # 文章格式:标题、段落、强调            result = f"# 办公文档\n\n"            result += f"> 生成时间: {datetime.datetime.now().strftime('%Y-%m-%d')}\n\n"            result += text            return result        else:            # 列表格式            items = [f"- {item}" for item in lines if item.strip()]            return "\n".join(items)    @staticmethod    def quick_reminder(message: str, minutes: int = 0) -> str:        """        快速提醒(模拟)        参数:            message: 提醒内容            minutes: 多少分钟后提醒(0表示立即提醒)        返回:            提醒信息        """        if minutes > 0:            reminder_time = datetime.datetime.now() + datetime.timedelta(minutes=minutes)            return f"⏰ 已设置提醒: '{message}'\n📅 将在 {reminder_time.strftime('%H:%M:%S')} 提醒你"        else:            return f"🔔 立即提醒: {message}\n📍 请及时处理"# 工具路由器(自动选择最合适的工具)class ToolRouter:    """智能工具路由器 - 根据用户输入自动选择合适的工具"""    @staticmethod    def route(query: str, **kwargs) -> str:        """        路由到合适的工具        参数:            query: 用户查询或命令            **kwargs: 额外参数        返回:            工具执行结果        """        tools = OfficeTools()        # 关键词映射        patterns = {            '时间|日期|现在几点了'lambda: tools.get_current_time(),            '计算|多少钱|合计'lambda: tools.calculate_safe(kwargs.get('expression', query)),            '创建日程|安排|计划'lambda: tools.create_schedule(kwargs.get('tasks', [])),            '复制文件|备份'lambda: tools.copy_file(kwargs.get('source'''), kwargs.get('dest''')),            '读取文件|打开'lambda: tools.read_file(kwargs.get('file_path''')),            '天气|气温'lambda: tools.smart_search('天气''天气'),            '提醒|闹钟'lambda: tools.quick_reminder(kwargs.get('message'''), kwargs.get('minutes'0)),        }        # 匹配关键词        for pattern, action in patterns.items():            if re.search(pattern, query):                return action()        # 默认返回帮助信息        return f"[工具路由器] 未匹配到合适工具\n您的请求: {query}\n支持的功能: {', '.join([k for k in patterns.keys()])}"# ==================== 使用示例 ====================if __name__ == "__main__":    tools = OfficeTools()    print("=" * 80)    print("办公工具集测试")    print("=" * 80)    # 测试时间管理    print("\n1. 时间管理工具:")    print(tools.get_current_time())    print(tools.calculate_workdays('2024-01-01''2024-01-31'))    # 测试文件处理    print("\n2. 文件处理工具:")    print(tools.list_directory('.''*.py'))    # 测试日程安排    print("\n3. 智能日程:")    tasks = [        {'name''完成项目报告''duration'3'deadline''2024-01-20''priority''high'},        {'name''团队会议''duration'1'deadline''2024-01-15''priority''high'},        {'name''邮件回复''duration'2'deadline''2024-01-14''priority''medium'}    ]    print(tools.create_schedule(tasks))    # 测试计算功能    print("\n4. 计算功能:")    print(tools.calculate_safe("15% of 200"))    print(tools.calculate_safe("(3+5)*2"))    # 测试会议议程    print("\n5. 会议议程:")    print(tools.generate_meeting_agenda("年终总结会议"60, ["张三""李四""王五"],                                        ["汇报年度工作""讨论明年计划""表彰优秀员工""总结发言"]))    # 测试单位转换    print("\n6. 单位转换:")    print(tools.convert_units(100'km''mile'))    print(tools.convert_units(25'c''f'))    # 测试路由器    print("\n7. 智能路由测试:")    print(ToolRouter.route("现在几点了"))
其中最重要的是代码里面的工具映射模块
        # 关键词映射        patterns = {            '时间|日期|现在几点了': lambda: tools.get_current_time(),            '计算|多少钱|合计': lambda: tools.calculate_safe(kwargs.get('expression', query)),            '创建日程|安排|计划': lambda: tools.create_schedule(kwargs.get('tasks', [])),            '复制文件|备份': lambda: tools.copy_file(kwargs.get('source'''), kwargs.get('dest''')),            '读取文件|打开': lambda: tools.read_file(kwargs.get('file_path''')),            '天气|气温': lambda: tools.smart_search('天气''天气'),            '提醒|闹钟': lambda: tools.quick_reminder(kwargs.get('message'''), kwargs.get('minutes'0)),        }

tools核心点:

  1. 模块化设计

    • 按功能分类:文件处理、数据处理、时间管理、沟通协作

    • 每个工具都有明确的输入输出类型提示

    • 统一的错误处理机制

  2. 办公场景针对性

    • 文件处理:支持txt、json、csv、目录浏览等办公常用操作

    • 数据处理:表格解析、单位转换、百分比计算

    • 时间管理:工作日计算、智能日程安排

    • 沟通工具:邮件格式化、会议议程生成

  3. 安全性增强

    • 严格过滤计算表达式的非法字符

    • 文件操作前检查路径有效性

    • 避免执行危险操作

  4. 易用性提升

    • 详细的函数文档字符串

    • 友好的错误提示信息

    • 支持多种输入格式自动识别

五:设计Agent,实现工具自动化
  1. 初始化:Agent 创建了自己的大脑 (AgentBrain) 和工具箱 (AgentTools)。
  2. 接收任务:run 方法启动,接收 task(如"我想去旅行")。
  3. 思考阶段:将任务和工具描述组合成 prompt,发送给大脑。大脑返回的文本中包含了它选择的"工具"和给工具的"指令"。
  4. 行动阶段:函数根据大脑的选择,调用对应的工具函数并返回结果。
  5. 反馈与总结:将原始任务、思考过程和行动结果再次发送给大脑,让它生成一个对用户友好的最终回复。
# agent.pyfrom brain import AgentBrainfrom tools import AgentToolsclass SimpleAgent:    """一个简单的任务规划 AI Agent"""    def __init__(self):        self.brain = AgentBrain()        # 静态工具类无需实例化        self.tools = AgentTools        # 定义 Agent 知道的工具列表及其描述,用于提示大脑        self.tool_descriptions = """        你可以使用以下工具:        1. 搜索工具:当你需要获取最新、未知的信息时使用,例如'搜索 北京天气'。        2. 计划工具:当你需要将多个步骤整理成计划时使用,例如'制定计划 [步骤1,步骤2]'。        3. 时间工具:当你需要知道当前时间时使用,指令就是'获取时间'。        4. 计算工具:当你需要进行数学计算时使用,例如'计算 3+5*2'。        """    def run(self, user_task):        """运行 Agent 的主循环"""        print(f"&#x1f3af; 用户任务: {user_task}")        print("=" * 40)        # 第一步:感知与初步思考        initial_prompt = f"""        你的角色是一个任务规划助手。        {self.tool_descriptions}        用户的任务是:{user_task}        请严格按照以下固定格式回答,不要添加额外内容:        思考:[简要分析任务需要什么]        工具:[选择要使用的工具名称,如果没有合适的就写'无']        指令:[发送给该工具的具体指令内容]        """        initial_response = self.brain.think(initial_prompt)        print("&#x1f9e0; 初始思考结果:")        print(initial_response)        print("-" * 20)        # 第二步:解析思考结果,提取工具和指令(鲁棒性优化)        lines = [line.strip() for line in initial_response.split('\n'if line.strip()]        tool_to_use = "无"        tool_instruction = ""        for line in lines:            if line.startswith("思考:"):                continue  # 跳过思考行            elif line.startswith("工具:"):                tool_to_use = line.replace("工具:""").strip()            elif line.startswith("指令:"):                tool_instruction = line.replace("指令:""").strip()        # 第三步:执行行动        result = self._use_tool(tool_to_use, tool_instruction)        print("&#x1f6e0;&#xfe0f;  执行结果:")        print(result)        print("=" * 40)        # 第四步:整合结果并反馈给用户        final_prompt = f"""        用户原始任务:{user_task}        你已经进行了思考并使用了工具。        思考过程:{initial_response}        工具执行结果:{result}        现在,请生成一段完整的、对用户的最终回复,直接给出有帮助的答案或计划,语言要自然友好。        """        final_response = self.brain.think(final_prompt)        print("&#x1f4a1; 最终回复给用户:")        print(final_response)        return final_response    def _use_tool(self, tool_name, instruction):        """根据工具名称调用具体的工具函数"""        # 统一工具名称匹配(兼容大小写/多余空格)        tool_name = tool_name.strip()        if tool_name == "搜索工具":            return self.tools.search_web(instruction)        elif tool_name == "计划工具":            # 兼容中英文逗号、括号,处理空指令            if not instruction:                return "[计划工具] 未提供计划步骤,无法生成日程。"            # 移除括号并拆分步骤(兼容 []/()/{} 括号)            clean_instr = instruction.strip('[](){}').strip()            # 同时支持中英文逗号拆分            steps = [s.strip() for s in clean_instr.replace(','',').split(','if s.strip()]            return self.tools.make_schedule(steps)        elif tool_name == "时间工具":            return self.tools.get_current_time()        elif tool_name == "计算工具":            return self.tools.calculate(instruction)        elif tool_name == "无":            return "[系统] 无需使用工具,直接回答用户即可。"        else:            return f"[系统] 未知工具:{tool_name},无法执行。"# 运行我们的 Agent!if __name__ == "__main__":    print("&#x1f916; 启动 SimpleAgent...")    my_agent = SimpleAgent()    # 测试几个不同的任务    test_tasks = [        "我想去旅行,帮我规划一下需要准备什么",        "现在几点了?",        "计算一下 15 的平方加上 20 的三分之一是多少",    ]    for task in test_tasks:        my_agent.run(task)        print("\n" + "#" * 50 + "\n")
再次重申,本文用的是deepseek-v4-flash,因为便宜,你可以平替为自己喜欢的模型基座。
我们看看代码最后运行的成果:
到这里,我们的初版demo,运行成功!!
ps:沙滩上全是人

最新文章

随机文章

基本 文件 流程 错误 SQL 调试
  1. 请求信息 : 2026-07-04 05:33:14 HTTP/2.0 GET : https://f.mffb.com.cn/a/491162.html
  2. 运行时间 : 0.099150s [ 吞吐率:10.09req/s ] 内存消耗:5,021.46kb 文件加载:140
  3. 缓存信息 : 0 reads,0 writes
  4. 会话信息 : SESSION_ID=bbf9f6b5f702e8fc55eea1c6db347f42
  1. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/public/index.php ( 0.79 KB )
  2. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/autoload.php ( 0.17 KB )
  3. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_real.php ( 2.49 KB )
  4. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/platform_check.php ( 0.90 KB )
  5. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/ClassLoader.php ( 14.03 KB )
  6. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/composer/autoload_static.php ( 4.90 KB )
  7. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper.php ( 8.34 KB )
  8. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/helper.php ( 2.19 KB )
  9. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/helper.php ( 1.47 KB )
  10. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/stubs/load_stubs.php ( 0.16 KB )
  11. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Exception.php ( 1.69 KB )
  12. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Facade.php ( 2.71 KB )
  13. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/deprecation-contracts/function.php ( 0.99 KB )
  14. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap.php ( 8.26 KB )
  15. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/polyfill-mbstring/bootstrap80.php ( 9.78 KB )
  16. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/Resources/functions/dump.php ( 1.49 KB )
  17. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-dumper/src/helper.php ( 0.18 KB )
  18. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/symfony/var-dumper/VarDumper.php ( 4.30 KB )
  19. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/App.php ( 15.30 KB )
  20. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-container/src/Container.php ( 15.76 KB )
  21. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/container/src/ContainerInterface.php ( 1.02 KB )
  22. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/provider.php ( 0.19 KB )
  23. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Http.php ( 6.04 KB )
  24. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Str.php ( 7.29 KB )
  25. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Env.php ( 4.68 KB )
  26. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/common.php ( 0.03 KB )
  27. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/helper.php ( 18.78 KB )
  28. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Config.php ( 5.54 KB )
  29. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/app.php ( 0.95 KB )
  30. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cache.php ( 0.78 KB )
  31. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/console.php ( 0.23 KB )
  32. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/cookie.php ( 0.56 KB )
  33. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/database.php ( 2.48 KB )
  34. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Env.php ( 1.67 KB )
  35. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/filesystem.php ( 0.61 KB )
  36. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/lang.php ( 0.91 KB )
  37. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/log.php ( 1.35 KB )
  38. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/middleware.php ( 0.19 KB )
  39. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/route.php ( 1.89 KB )
  40. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/session.php ( 0.57 KB )
  41. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/trace.php ( 0.34 KB )
  42. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/config/view.php ( 0.82 KB )
  43. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/event.php ( 0.25 KB )
  44. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Event.php ( 7.67 KB )
  45. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/service.php ( 0.13 KB )
  46. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/AppService.php ( 0.26 KB )
  47. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Service.php ( 1.64 KB )
  48. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Lang.php ( 7.35 KB )
  49. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/lang/zh-cn.php ( 13.70 KB )
  50. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/Error.php ( 3.31 KB )
  51. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/RegisterService.php ( 1.33 KB )
  52. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/services.php ( 0.14 KB )
  53. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/PaginatorService.php ( 1.52 KB )
  54. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ValidateService.php ( 0.99 KB )
  55. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/service/ModelService.php ( 2.04 KB )
  56. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Service.php ( 0.77 KB )
  57. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Middleware.php ( 6.72 KB )
  58. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/initializer/BootService.php ( 0.77 KB )
  59. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Paginator.php ( 11.86 KB )
  60. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-validate/src/Validate.php ( 63.20 KB )
  61. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/Model.php ( 23.55 KB )
  62. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Attribute.php ( 21.05 KB )
  63. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/AutoWriteData.php ( 4.21 KB )
  64. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/Conversion.php ( 6.44 KB )
  65. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/DbConnect.php ( 5.16 KB )
  66. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/ModelEvent.php ( 2.33 KB )
  67. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/concern/RelationShip.php ( 28.29 KB )
  68. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Arrayable.php ( 0.09 KB )
  69. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/contract/Jsonable.php ( 0.13 KB )
  70. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/model/contract/Modelable.php ( 0.09 KB )
  71. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Db.php ( 2.88 KB )
  72. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/DbManager.php ( 8.52 KB )
  73. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Log.php ( 6.28 KB )
  74. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Manager.php ( 3.92 KB )
  75. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerTrait.php ( 2.69 KB )
  76. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/log/src/LoggerInterface.php ( 2.71 KB )
  77. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cache.php ( 4.92 KB )
  78. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/psr/simple-cache/src/CacheInterface.php ( 4.71 KB )
  79. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/helper/Arr.php ( 16.63 KB )
  80. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/driver/File.php ( 7.84 KB )
  81. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/cache/Driver.php ( 9.03 KB )
  82. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/CacheHandlerInterface.php ( 1.99 KB )
  83. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/Request.php ( 0.09 KB )
  84. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Request.php ( 55.78 KB )
  85. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/middleware.php ( 0.25 KB )
  86. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Pipeline.php ( 2.61 KB )
  87. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/TraceDebug.php ( 3.40 KB )
  88. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/middleware/SessionInit.php ( 1.94 KB )
  89. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Session.php ( 1.80 KB )
  90. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/driver/File.php ( 6.27 KB )
  91. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/SessionHandlerInterface.php ( 0.87 KB )
  92. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/session/Store.php ( 7.12 KB )
  93. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Route.php ( 23.73 KB )
  94. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleName.php ( 5.75 KB )
  95. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Domain.php ( 2.53 KB )
  96. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleGroup.php ( 22.43 KB )
  97. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Rule.php ( 26.95 KB )
  98. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/RuleItem.php ( 9.78 KB )
  99. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/route/app.php ( 1.72 KB )
  100. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/Route.php ( 4.70 KB )
  101. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/dispatch/Controller.php ( 4.74 KB )
  102. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/route/Dispatch.php ( 10.44 KB )
  103. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/controller/Index.php ( 4.81 KB )
  104. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/app/BaseController.php ( 2.05 KB )
  105. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/facade/Db.php ( 0.93 KB )
  106. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/connector/Mysql.php ( 5.44 KB )
  107. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/PDOConnection.php ( 52.47 KB )
  108. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Connection.php ( 8.39 KB )
  109. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/ConnectionInterface.php ( 4.57 KB )
  110. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/builder/Mysql.php ( 16.58 KB )
  111. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Builder.php ( 24.06 KB )
  112. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseBuilder.php ( 27.50 KB )
  113. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/Query.php ( 15.71 KB )
  114. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/BaseQuery.php ( 45.13 KB )
  115. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TimeFieldQuery.php ( 7.43 KB )
  116. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/AggregateQuery.php ( 3.26 KB )
  117. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ModelRelationQuery.php ( 20.07 KB )
  118. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ParamsBind.php ( 3.66 KB )
  119. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/ResultOperation.php ( 7.01 KB )
  120. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/WhereQuery.php ( 19.37 KB )
  121. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/JoinAndViewQuery.php ( 7.11 KB )
  122. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/TableFieldInfo.php ( 2.63 KB )
  123. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-orm/src/db/concern/Transaction.php ( 2.77 KB )
  124. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/driver/File.php ( 5.96 KB )
  125. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/LogHandlerInterface.php ( 0.86 KB )
  126. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/log/Channel.php ( 3.89 KB )
  127. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/event/LogRecord.php ( 1.02 KB )
  128. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-helper/src/Collection.php ( 16.47 KB )
  129. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/facade/View.php ( 1.70 KB )
  130. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/View.php ( 4.39 KB )
  131. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Response.php ( 8.81 KB )
  132. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/response/View.php ( 3.29 KB )
  133. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/Cookie.php ( 6.06 KB )
  134. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-view/src/Think.php ( 8.38 KB )
  135. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/framework/src/think/contract/TemplateHandlerInterface.php ( 1.60 KB )
  136. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/Template.php ( 46.61 KB )
  137. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/driver/File.php ( 2.41 KB )
  138. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-template/src/template/contract/DriverInterface.php ( 0.86 KB )
  139. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/runtime/temp/067d451b9a0c665040f3f1bdd3293d68.php ( 11.98 KB )
  140. /yingpanguazai/ssd/ssd1/www/f.mffb.com.cn/vendor/topthink/think-trace/src/Html.php ( 4.42 KB )
  1. CONNECT:[ UseTime:0.000547s ] mysql:host=127.0.0.1;port=3306;dbname=f_mffb;charset=utf8mb4
  2. SHOW FULL COLUMNS FROM `fenlei` [ RunTime:0.000993s ]
  3. SELECT * FROM `fenlei` WHERE `fid` = 0 [ RunTime:0.000338s ]
  4. SELECT * FROM `fenlei` WHERE `fid` = 63 [ RunTime:0.004262s ]
  5. SHOW FULL COLUMNS FROM `set` [ RunTime:0.000687s ]
  6. SELECT * FROM `set` [ RunTime:0.004034s ]
  7. SHOW FULL COLUMNS FROM `article` [ RunTime:0.000798s ]
  8. SELECT * FROM `article` WHERE `id` = 491162 LIMIT 1 [ RunTime:0.000793s ]
  9. UPDATE `article` SET `lasttime` = 1783114394 WHERE `id` = 491162 [ RunTime:0.006509s ]
  10. SELECT * FROM `fenlei` WHERE `id` = 66 LIMIT 1 [ RunTime:0.000335s ]
  11. SELECT * FROM `article` WHERE `id` < 491162 ORDER BY `id` DESC LIMIT 1 [ RunTime:0.000579s ]
  12. SELECT * FROM `article` WHERE `id` > 491162 ORDER BY `id` ASC LIMIT 1 [ RunTime:0.002073s ]
  13. SELECT * FROM `article` WHERE `id` < 491162 ORDER BY `id` DESC LIMIT 10 [ RunTime:0.002619s ]
  14. SELECT * FROM `article` WHERE `id` < 491162 ORDER BY `id` DESC LIMIT 10,10 [ RunTime:0.003647s ]
  15. SELECT * FROM `article` WHERE `id` < 491162 ORDER BY `id` DESC LIMIT 20,10 [ RunTime:0.002699s ]
0.100814s