乐于分享
好东西不私藏

【AI Agent零基础入门⑧】Agent案例实战——构建智能助手

【AI Agent零基础入门⑧】Agent案例实战——构建智能助手

前言

欢迎来到AI Agent零基础入门教程的第八课!经过前七节课的学习,我们已经掌握了AI Agent开发的核心知识。本节课我们将进入实战环节,综合运用所学知识,构建一个功能完备的个人智能助手应用。

这个智能助手将具备以下核心功能: - 日程管理(日程查询、添加、提醒) - 信息搜索(网络搜索、百科查询) - 任务管理(待办事项、优先级排序) - 记忆功能(记住用户偏好、对话历史) - 智能对话(自然语言交互、上下文理解)

通过本节课的学习,你将掌握如何将零散的知识点整合成完整的应用系统。

项目需求分析

功能需求

┌─────────────────────────────────────────────────────────────┐│                    个人智能助手 功能架构                      ├─────────────────────────────────────────────────────────────┤│                                                             ││  ┌─────────────────────────────────────────────────────┐   ││  │                   用户交互层                          │   ││  │         (CLI界面 / API接口 / Web界面)                │   ││  └─────────────────────────────────────────────────────┘   ││                            │                                ││  ┌─────────────────────────────────────────────────────┐   ││  │                   核心功能层                          │   ││  │  ┌──────────┐ ┌──────────┐ ┌──────────┐ ┌────────┐ │  ││  │  │ 日程管理 │ │ 任务管理 │ │ 知识检索 │ │ 提醒   │ │  ││  │  └──────────┘ └──────────┘ └──────────┘ └────────┘ │  ││  └─────────────────────────────────────────────────────┘   ││                            │                                ││  ┌─────────────────────────────────────────────────────┐   ││  │                   Agent大脑层                        │   ││  │     ┌─────────────────────────────────────────┐     │   ││  │     │  意图识别 → 任务分解 → 工具调用 → 结果整合 │    │  ││  │     └─────────────────────────────────────────┘     │   ││  └─────────────────────────────────────────────────────┘   ││                            │                                ││  ┌─────────────────────────────────────────────────────┐   ││  │                   记忆存储层                          │   ││  │     ┌──────────┐ ┌──────────┐ ┌──────────┐          │   ││  │     │对话记忆   │ │用户偏好  │ │知识库   │          │   ││  │     └──────────┘ └──────────┘ └──────────┘          │   ││  └─────────────────────────────────────────────────────┘   ││                                                             │└─────────────────────────────────────────────────────────────┘

技术架构

框架LangChain

语言模型OpenAI GPT-3.5/4

数据存储:本地JSON文件(SQLite可选)

接口:命令行界面(CLI)

项目结构设计

目录结构

ai_personal_assistant/├── config/│   └── settings.py          # 配置文件├── tools/│   ├── __init__.py│   ├── calendar_tools.py     # 日历工具│   ├── task_tools.py         # 任务工具│   ├── search_tools.py       # 搜索工具│   └── memory_tools.py       # 记忆工具├── memory/│   ├── __init__.py│   └── memory_manager.py     # 记忆管理├── agent/│   ├── __init__.py│   ├── assistant.py          # 助手主类│   └── prompts.py            # 提示模板├── data/│   ├── schedules.json       # 日程数据│   ├── tasks.json           # 任务数据│   └── user_profile.json    # 用户信息├── main.py                   # 主程序入口├── requirements.txt         # 依赖列表└── README.md                # 说明文档

完整代码实现

1. 配置模块

创建config/settings.py

"""个人智能助手 - 配置模块管理应用程序的配置信息"""import osfrom pathlib import Pathfrom dotenv import load_dotenv加载环境变量load_dotenv()项目根目录PROJECT_ROOT = Path(__file__).parent.parent数据目录DATA_DIR = PROJECT_ROOT /"data"DATA_DIR.mkdir(exist_ok=True)数据文件路径SCHEDULES_FILE = DATA_DIR /"schedules.json"TASKS_FILE = DATA_DIR /"tasks.json"USER_PROFILE_FILE = DATA_DIR /"user_profile.json"MEMORY_FILE = DATA_DIR /"memory.json"# API配置OPENAI_API_KEY = os.getenv("OPENAI_API_KEY""")OPENAI_MODEL = os.getenv("OPENAI_MODEL""gpt-3.5-turbo")OPENAI_TEMPERATURE =0.7# Agent配置MAX_ITERATIONS =15VERBOSE =TrueHANDLE_PARSING_ERRORS =True记忆配置MAX_MEMORY_MESSAGES =50MEMORY_SUMMARY_THRESHOLD =10

2. 工具模块

创建tools/calendar_tools.py

"""个人智能助手 - 日历工具提供日程管理相关的工具函数"""from datetime import datetime, timedeltafrom typing import List, Dict, Optionalimport jsonfrom pathlib import Pathfrom config.settings import SCHEDULES_FILEdef load_schedules() -> List[Dict]:"""加载日程数据"""if SCHEDULES_FILE.exists():withopen(SCHEDULES_FILE, 'r', encoding='utf-8'as f:return json.load(f)return []def save_schedules(schedules: List[Dict]):"""保存日程数据"""withopen(SCHEDULES_FILE, 'w', encoding='utf-8'as f:        json.dump(schedules, f, ensure_ascii=False, indent=2)def get_current_time() ->str:"""获取当前时间"""    now = datetime.now()return now.strftime("%Y%m%d %H:%M:%S %A")def add_schedule(title: str, date: str, time: Optional[str=None,                description: str=""->str:"""添加日程    Args:        title: 日程标题        date: 日期(YYYY-MM-DD格式)        time: 时间(HH:MM格式,可选)        description: 描述(可选)    Returns:操作结果    """    schedules = load_schedules()    new_schedule = {"id"len(schedules) +1,"title": title,"date": date,"time": time or"全天","description": description,"created_at": datetime.now().isoformat(),"completed"False    }    schedules.append(new_schedule)    save_schedules(schedules)returnf"日程已添加:{title},日期:{date},时间:{new_schedule['time']}"def list_schedules(date: Optional[str=None,                   include_completed: bool=False->str:"""列出日程    Args:        date: 日期筛选(可选)        include_completed: 是否包含已完成的日程    Returns:日程列表    """    schedules = load_schedules()ifnot schedules:return"目前没有任何日程"筛选    filtered = []for s in schedules:if date and s['date'!= date:continueifnot include_completed and s.get('completed'False):continue        filtered.append(s)ifnot filtered:returnf"{date or'所有'}日期没有日程记录"格式化输出    result = ["�� 日程列表:\n"]按日期分组    by_date = {}for s in filtered:        d = s['date']if d notin by_date:            by_date[d] = []        by_date[d].append(s)for d, items insorted(by_date.items()):        result.append(f"\n��{d}:")for item in items:            status ="✓"if item.get('completed'else"○"            result.append(f"  {status} [{item['time']}{item['title']}"            )return"\n".join(result)def complete_schedule(schedule_id: int->str:"""标记日程完成    Args:        schedule_id: 日程ID    Returns:操作结果    """    schedules = load_schedules()for s in schedules:if s['id'== schedule_id:            s['completed'=True            save_schedules(schedules)returnf"日程已完成:{s['title']}"returnf"未找到ID{schedule_id}的日程"def delete_schedule(schedule_id: int->str:"""删除日程    Args:        schedule_id: 日程ID    Returns:操作结果    """    schedules = load_schedules()    original_count =len(schedules)    schedules = [s for s in schedules if s['id'!= schedule_id]iflen(schedules) == original_count:returnf"未找到ID{schedule_id}的日程"    save_schedules(schedules)returnf"日程已删除"def get_upcoming(days: int=7->str:"""获取即将到来的日程    Args:        days: 天数    Returns:即将到来的日程列表    """    schedules = load_schedules()    now = datetime.now()    end_date = now + timedelta(days=days)    upcoming = []for s in schedules:if s.get('completed'):continuetry:            schedule_date = datetime.strptime(s['date'], "%Y-%m-%d")if now <= schedule_date <= end_date:                upcoming.append(s)exceptValueError:continueifnot upcoming:returnf"未来{days}天内没有日程安排"按日期排序    upcoming.sort(key=lambda x: x['date'])    result = [f"�� 未来{days}天的日程:\n"]for s in upcoming:        result.append(f"  �� {s['date']} [{s['time']}{s['title']}")return"\n".join(result)

创建tools/task_tools.py

"""个人智能助手 - 任务工具提供任务管理相关的工具函数"""from datetime import datetimefrom typing import List, Dict, Optionalimport jsonfrom config.settings import TASKS_FILEdef load_tasks() -> List[Dict]:"""加载任务数据"""if TASKS_FILE.exists():withopen(TASKS_FILE, 'r', encoding='utf-8'as f:return json.load(f)return []def save_tasks(tasks: List[Dict]):"""保存任务数据"""withopen(TASKS_FILE, 'w', encoding='utf-8'as f:        json.dump(tasks, f, ensure_ascii=False, indent=2)def add_task(title: str, priority: str="medium",            due_date: Optional[str=None,            description: str=""->str:"""添加任务    Args:        title: 任务标题        priority: 优先级(high/medium/low        due_date: 截止日期(YYYY-MM-DD格式)        description: 描述    Returns:操作结果    """    tasks = load_tasks()优先级映射    priority_map = {"high""�� 高""medium""�� 中""low""�� 低"}    priority_text = priority_map.get(priority, "�� 中")    new_task = {"id"len(tasks) +1,"title": title,"priority": priority,"priority_text": priority_text,"due_date": due_date,"description": description,"created_at": datetime.now().isoformat(),"completed"False    }    tasks.append(new_task)    save_tasks(tasks)    result =f"任务已添加:{title},优先级:{priority_text}"if due_date:        result +=f",截止日期:{due_date}"return resultdef list_tasks(status: str="pending",               priority: Optional[str=None->str:"""列出任务    Args:        status: 状态(pending/completed/all        priority: 优先级筛选(high/medium/low    Returns:任务列表    """    tasks = load_tasks()ifnot tasks:return"目前没有任何任务"筛选    filtered = []for t in tasks:if status =="pending"and t.get('completed'):continueif status =="completed"andnot t.get('completed'):continueif priority and t.get('priority'!= priority:continue        filtered.append(t)ifnot filtered:        status_text = {"pending""待完成","completed""已完成","all""所有"        }returnf"没有{status_text.get(status, '')}的任务"按优先级和创建时间排序    priority_order = {"high"0"medium"1"low"2}    filtered.sort(key=lambda x: (        priority_order.get(x.get('priority''medium'), 1),        x.get('created_at''')    ))    result = ["�� 任务列表:\n"]按优先级分组显示    by_priority = {"high": [], "medium": [], "low": []}for t in filtered:        p = t.get('priority''medium')if p in by_priority:            by_priority[p].append(t)    priority_labels = {"high""�� 高优先级","medium""�� 中优先级","low""�� 低优先级"    }for p, label in priority_labels.items():        items = by_priority.get(p, [])if items:            result.append(f"\n{label}:")for item in items:                status ="✓"if item.get('completed'else"○"                due =f"[截止:{item['due_date']}]"if item.get('due_date'else""                result.append(f"  {status} [{item['id']}{item['title']}{due}"                )统计    pending =sum(1for t in tasks ifnot t.get('completed'))    completed =sum(1for t in tasks if t.get('completed'))    result.append(f"\n��统计:待完成{pending},已完成{completed}")return"\n".join(result)def complete_task(task_id: int->str:"""标记任务完成"""    tasks = load_tasks()for t in tasks:if t['id'== task_id:            t['completed'=True            save_tasks(tasks)returnf"任务已完成:{t['title']}"returnf"未找到ID{task_id}的任务"def delete_task(task_id: int->str:"""删除任务"""    tasks = load_tasks()    original_count =len(tasks)    tasks = [t for t in tasks if t['id'!= task_id]iflen(tasks) == original_count:returnf"未找到ID{task_id}的任务"    save_tasks(tasks)returnf"任务已删除"def get_overdue() ->str:"""获取过期任务"""    tasks = load_tasks()    today = datetime.now().strftime("%Y-%m-%d")    overdue = []for t in tasks:if t.get('completed'):continueif t.get('due_date'and t['due_date'< today:            overdue.append(t)ifnot overdue:return"没有过期任务,干得不错!"    result = ["⚠️ 过期任务:\n"]for t in overdue:        result.append(f"  �� [{t['id']}{t['title']} (截止{t['due_date']})"        )return"\n".join(result)

3. 记忆模块

创建memory/memory_manager.py

"""个人智能助手 - 记忆管理管理用户偏好和对话历史"""import jsonfrom datetime import datetimefrom pathlib import Pathfrom typing import Dict, List, Optionalfrom config.settings import USER_PROFILE_FILE, MEMORY_FILEclass UserProfile:"""用户画像管理"""def__init__(self):self.profile =self._load_profile()def _load_profile(self-> Dict:"""加载用户画像"""if USER_PROFILE_FILE.exists():withopen(USER_PROFILE_FILE, 'r', encoding='utf-8'as f:return json.load(f)return {"name""用户","preferences": {},"created_at": datetime.now().isoformat()        }def _save_profile(self):"""保存用户画像"""withopen(USER_PROFILE_FILE, 'w', encoding='utf-8'as f:            json.dump(self.profile, f, ensure_ascii=False, indent=2)def set_name(self, name: str):"""设置用户名"""self.profile["name"= nameself._save_profile()returnf"好的,我已经记住您的名字是{name}"def set_preference(self, key: str, value: str):"""设置偏好"""self.profile["preferences"][key] = valueself._save_profile()returnf"已记录您的偏好:{key} = {value}"def get_profile(self->str:"""获取用户画像"""        name =self.profile.get("name""用户")        preferences =self.profile.get("preferences", {})        result = [f"�� 用户信息:\n姓名:{name}"]if preferences:            result.append("  偏好设置:")for k, v in preferences.items():                result.append(f"    - {k}{v}")return"\n".join(result)class ConversationMemory:"""对话记忆管理"""def__init__(self, max_messages: int=50):self.max_messages = max_messagesself.messages =self._load_memory()def _load_memory(self-> List[Dict]:"""加载对话记忆"""if MEMORY_FILE.exists():withopen(MEMORY_FILE, 'r', encoding='utf-8'as f:return json.load(f)return []def _save_memory(self):"""保存对话记忆"""withopen(MEMORY_FILE, 'w', encoding='utf-8'as f:            json.dump(self.messages, f, ensure_ascii=False, indent=2)def add_message(self, role: str, content: str):"""添加消息"""self.messages.append({"role": role,"content": content,"timestamp": datetime.now().isoformat()        })限制记忆长度iflen(self.messages) >self.max_messages:self.messages =self.messages[-self.max_messages:]self._save_memory()def get_recent_messages(self, count: int=10-> List[Dict]:"""获取最近的消息"""returnself.messages[-count:]def clear_memory(self):"""清空记忆"""self.messages = []self._save_memory()return"对话记忆已清空"def search_memory(self, keyword: str->str:"""搜索记忆"""        results = []for msg inself.messages:if keyword.lower() in msg['content'].lower():                results.append(msg)ifnot results:returnf"没有找到关于'{keyword}'的记忆"        result = [f"�� 找到{len(results)}条相关记忆:\n"]for i, msg inenumerate(results[-5:], 1):  最多显示5            result.append(f"{i}. [{msg['role']}]: {msg['content'][:100]}...")return"\n".join(result)

4. Agent主类

创建agent/assistant.py

"""个人智能助手 - 智能助手主类整合所有功能,构建完整的智能助手"""import osfrom datetime import datetimefrom dotenv import load_dotenvfrom langchain_openai import OpenAIfrom langchain.agents import AgentType, initialize_agent, load_toolsfrom langchain.memory import ConversationBufferMemoryfrom langchain_core.tools import toolfrom config.settings import (    OPENAI_MODEL, OPENAI_TEMPERATURE,    MAX_ITERATIONS, VERBOSE, HANDLE_PARSING_ERRORS)from tools.calendar_tools import (    get_current_time, add_schedule, list_schedules,    complete_schedule, delete_schedule, get_upcoming)from tools.task_tools import (    add_task, list_tasks, complete_task, delete_task, get_overdue)from memory.memory_manager import UserProfile, ConversationMemory加载环境变量load_dotenv()定义智能助手可用的工具@tooldef get_time() ->str:"""获取当前日期和时间    Returns:当前日期时间字符串    """return get_current_time()@tooldef add_calendar_event(title: str, date: str, time: str="全天",                       description: str=""->str:"""添加日历日程事件    Args:        title: 日程标题,必填        date: 日期,格式YYYY-MM-DD,必填        time: 时间,如"09:00""全天",默认全天        description: 事件描述,可选    Returns:操作结果字符串    """return add_schedule(title, date, time, description)@tooldef view_schedules(date: str="", include_completed: bool=False->str:"""查看日历日程    Args:        date: 日期筛选,格式YYYY-MM-DD,空表示查看所有        include_completed: 是否包含已完成的日程    Returns:日程列表字符串    """return list_schedules(date if date elseNone, include_completed)@tooldef complete_calendar_event(event_id: int->str:"""标记日历事件为已完成    Args:        event_id: 日程ID,必填    Returns:操作结果    """return complete_schedule(event_id)@tooldef delete_calendar_event(event_id: int->str:"""删除日历事件    Args:        event_id: 日程ID,必填    Returns:操作结果    """return delete_schedule(event_id)@tooldef get_upcoming_events(days: int=7->str:"""获取即将到来的日程    Args:        days: 天数,默认7    Returns:即将到来的日程列表    """return get_upcoming(days)@tooldef add_todo_item(title: str, priority: str="medium",                  due_date: str="", description: str=""->str:"""添加待办事项    Args:        title: 任务标题,必填        priority: 优先级,high/medium/low,默认medium        due_date: 截止日期,格式YYYY-MM-DD,可选        description: 任务描述,可选    Returns:操作结果    """return add_task(title, priority, due_date if due_date elseNone, description)@tooldef view_todos(status: str="pending", priority: str=""->str:"""查看待办事项    Args:        status: 状态筛选,pending/completed/all,默认pending        priority: 优先级筛选,high/medium/low,空表示全部    Returns:任务列表    """return list_tasks(status, priority if priority elseNone)@tooldef complete_todo_item(task_id: int->str:"""标记待办事项为已完成    Args:        task_id: 任务ID,必填    Returns:操作结果    """return complete_task(task_id)@tooldef delete_todo_item(task_id: int->str:"""删除待办事项    Args:        task_id: 任务ID,必填    Returns:操作结果    """return delete_task(task_id)@tooldef check_overdue_todos() ->str:"""检查过期任务    Returns:过期任务列表    """return get_overdue()class PersonalAssistant:"""个人智能助手整合日历、任务、记忆等功能    """def__init__(self):"""初始化智能助手        """print("�� 正在初始化个人智能助手...\n")初始化用户画像和对话记忆self.user_profile = UserProfile()self.conversation_memory = ConversationMemory()初始化语言模型self.llm = OpenAI(            temperature=OPENAI_TEMPERATURE,            model=OPENAI_MODEL,            max_tokens=2000        )定义助手工具self.tools = [            get_time,            add_calendar_event,            view_schedules,            complete_calendar_event,            delete_calendar_event,            get_upcoming_events,            add_todo_item,            view_todos,            complete_todo_item,            delete_todo_item,            check_overdue_todos        ]创建记忆self.memory = ConversationBufferMemory(            memory_key="chat_history",            return_messages=True,            output_key="output"        )创建Agentself.agent =self._create_agent()print("✅ 智能助手初始化完成!\n")def _create_agent(self):"""创建Agent"""系统提示词        system_prompt =f"""你是一个专业、友好的个人智能助手。你的职责:1. 帮助用户管理日程和待办事项2. 提供有用的信息和建议3. 记住用户的偏好和重要信息4. 以友好、专业的方式与用户交流核心能力:日程管理:添加、查看、标记完成、删除日程任务管理:添加、查看、标记完成、删除待办事项信息查询:获取当前时间、天气等记忆功能:记住用户偏好和对话历史交流原则:简洁明了,直接回答用户问题主动提供有用的建议确认用户的操作并给出反馈在合适的时候提醒重要事项用户名:{self.user_profile.profile.get('name''用户')}"""return initialize_agent(self.tools,self.llm,            agent=AgentType.CONVERSATIONAL_REACT_DESCRIPTION,            memory=self.memory,            prompt=system_prompt,            verbose=VERBOSE,            handle_parsing_errors=HANDLE_PARSING_ERRORS,            max_iterations=MAX_ITERATIONS        )def chat(self, message: str->str:"""与助手对话        Args:            message: 用户消息        Returns:助手回复        """记录用户消息self.conversation_memory.add_message("user", message)调用Agent        response =self.agent.run(message)记录助手回复self.conversation_memory.add_message("assistant", response)return responsedef run_interactive(self):"""运行交互式对话        """print("""╔════════════════════════════════════════════════════════════╗║                                                            ║║              �� 个人智能助手 交互模式                     ║                                                            ║║    我可以帮助你:                                          ║    �� 日程管理 添加、查看、标记完成日程                  ║    �� 任务管理 添加、查看、标记完成任务                  ║    �� 信息查询 时间、日期等                              ║    �� 智能建议 根据你的情况提供建议                      ║                                                            ║║    输入 'exit' 退出                                        ║    输入 'help' 查看帮助                                    ║                                                            ║╚════════════════════════════════════════════════════════════╝        """)问候语        user_name =self.user_profile.profile.get('name''用户')print(f"\n��你好,{user_name}!有什么可以帮助你的吗?\n")whileTrue:try:                user_input =input("�� 你:").strip()if user_input.lower() in ['exit''quit''退出']:print("\n��再见!祝你一天愉快!")breakif user_input.lower() in ['help''帮助']:print("""��使用帮助:【日程管理】  - "查看我的日程"  - "添加明天9点的会议"  - "标记日程3完成"  - "删除日程2"【任务管理】  - "查看我的待办"  - "添加今天要完成的重要任务"  - "标记任务1完成"  - "查看过期任务"【信息查询】  - "现在几点了?"  - "查看接下来一周的日程"【其他】  - "帮我总结一下本周的任务"  - "我有哪些待完成的事项?"                    """)continueifnot user_input:continueprint("\n��思考中...\n")                response =self.chat(user_input)print(f"�� 助手:{response}\n")exceptKeyboardInterrupt:print("\n\n��再见!")breakexceptExceptionas e:print(f"\n❌ 发生错误:{e}\n")def main():"""主函数"""    assistant = PersonalAssistant()    assistant.run_interactive()if__name__=="__main__":    main()

5. 主程序入口

创建main.py

"""个人智能助手 - 主程序入口启动并运行智能助手应用"""import sysimport os添加项目根目录到路径sys.path.insert(0, os.path.dirname(os.path.abspath(__file__)))from agent.assistant import PersonalAssistantdef main():"""主函数"""print("""╔════════════════════════════════════════════════════════════╗║                                                            ║║              �� 个人智能助手 v1.0                           ║║                                                            ║║              Python AI Agent 实战项目                      ║                                                            ║╚════════════════════════════════════════════════════════════╝    """)try:        assistant = PersonalAssistant()        assistant.run_interactive()exceptKeyboardInterrupt:print("\n\n��程序已退出。再见!")exceptExceptionas e:print(f"\n❌ 程序发生错误:{e}")print("请检查:")print("  1. 是否已设置 OPENAI_API_KEY 环境变量")print("  2. 网络连接是否正常")print("  3. 依赖包是否正确安装")raiseif__name__=="__main__":    main()

6. 依赖文件

创建requirements.txt

langchain>=0.1.0langchain-core>=0.1.0langchain-openai>=0.0.2openai>=0.27.0python-dotenv>=1.0.0

运行演示

初始化项目

创建项目目录mkdir ai_personal_assistantcd ai_personal_assistant创建虚拟环境python-m venv venvsource venv/bin/activate  # Linux/Mac# venv\Scripts\activate   # Windows安装依赖pip install -r requirements.txt配置环境变量cp .env.example .env编辑.env文件,添加你的API密钥

运行应用

python main.py

示例对话

��你好,用户!有什么可以帮助你的吗?��你:帮我添加一个明天的会议��助手:好的,我来帮你添加明天的会议。请问会议的具体时间是什么时候?��你:下午2点开始��助手:好的,已添加明天14:00的会议日程。��你:查看我的待办事项��助手:��任务列表:��高优先级:○ [1] 完成项目报告 [截止:2024-01-20]��中优先级:○ [2] 回复邮件��统计:待完成 2,已完成 0��你:现在几点了?��助手:现在是2024115日 14:30:25 星期一

功能扩展建议

1. 添加Web界面

使用Streamlit快速构建Web界面:

import streamlit as stfrom agent.assistant import PersonalAssistantst.title("�� 个人智能助手")if"assistant"notin st.session_state:    st.session_state.assistant = PersonalAssistant()user_input = st.text_input("请输入你的问题:", key="input")if user_input:    response = st.session_state.assistant.chat(user_input)    st.text_area("助手回复:", value=response, height=100)

2. 添加数据库支持

使用SQLite存储数据:

import sqlite3def init_database():    conn = sqlite3.connect('assistant.db')    c = conn.cursor()    c.execute('''CREATE TABLE IF NOT EXISTS schedules                 (id INTEGER PRIMARY KEY, title TEXT, date TEXT,                  time TEXT, description TEXT, completed INTEGER)''')    c.execute('''CREATE TABLE IF NOT EXISTS tasks                 (id INTEGER PRIMARY KEY, title TEXT, priority TEXT,                  due_date TEXT, description TEXT, completed INTEGER)''')    conn.commit()    conn.close()

3. 添加API服务

使用FastAPI提供服务:

from fastapi import FastAPIfrom pydantic import BaseModelfrom agent.assistant import PersonalAssistantapp = FastAPI()assistant = PersonalAssistant()class ChatRequest(BaseModel):    message: str@app.post("/chat")def chat(request: ChatRequest):    response = assistant.chat(request.message)return {"response": response}

常见问题与解决方案

问题1API调用失败

解决方案 1. 检查API密钥是否正确配置 2. 确认网络代理设置 3. 查看API额度是否充足

问题2Agent回复不准确

解决方案 1. 优化系统提示词 2. 提供更多示例帮助Agent理解 3. 调整temperature参数

问题3:数据存储问题

解决方案 1. 检查文件路径是否正确 2. 确认目录是否有写入权限 3. 考虑使用数据库替代JSON文件

总结与下节预告

本节课,我们构建了一个完整的个人智能助手应用:

1.项目架构:设计了清晰的项目结构

2.工具模块:实现了日历和任务管理工具

3.记忆模块:实现了用户画像和对话记忆

4.Agent整合:将所有功能整合到一个智能Agent中

5.交互界面:实现了友好的命令行交互

下一节课,我们将学习Agent安全与错误处理,确保我们的应用能够稳定、安全地运行。

敬请期待!

练习题

1.实践题:为助手添加更多功能(如天气查询、提醒功能)

2.思考题:如何优化助手的响应速度?

3.拓展题:使用Streamlit构建Web界面版本

4.挑战题:为助手添加多语言支持

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