Agent

B站视频链接:https://www.bilibili.com/video/BV1aeLqzUE6L?spm_id_from=333.788.videopod.sections\&vd_source=0a100cb9d25855cbc65bcb483a8a5a84

  • user prompt: 我们通过聊天框发送给AI模型的消息;
  • system prompt: 用来描述AI的角色、性格、背景信息、语气等;

每次用户发送user prompt的时候,系统会自动把system prompt发送给AI

  • function calling: 规定了AI使用工具时应该返回的格式;
  • MCP: 是一个通信协议,专门用来规范Agent和Tool服务之间是怎么交互的,称Tool服务为MCP server,调用它的Agent为MCP client,MCP实际上用来帮助Agent管理工具、资源和提示词;

MCP server可以和Agent部署在一起,通过stdio标准输入输出来通信,也可以部署在远程,通过HTTP网络协议来访问;

B站视频链接:https://www.bilibili.com/video/BV1UMVKzEESL?spm_id_from=333.788.videopod.sections\&vd_source=0a100cb9d25855cbc65bcb483a8a5a84

需要准备的:

  • 一个Gemini模型的API KEY

  • 一个Python环境

  • 安装必要的Python库:pydantic_ai, dotenv

  • 一个.env文件,用来存储API KEY

  • 一个Agent_demo目录,用来存放Agent的代码

    • main.py: 用来运行Agent的代码
    • tools.py: 用来定义Agent可以调用的工具函数
    • .env: 用来存储API KEY
    • base_dir: 用来存储Agent可以访问的文件目录

    main.py

python 复制代码
from pydantic_ai.models.gemini import GeminiModel
from pydantic_ai import Agent

from dotenv import load_dotenv # 加载.env文件中的API KEY
import tools

load_dotenv()
model = GeminiModel("gemini-2.5-flash-preview-04-17")

agent = Agent(model,
             system_prompt="You are an experienced programmer",
             tools=[tools.read_file, tools.list_files, tools.rename_file])

def main():
   history = []
   while True:
       user_input = input("Input: ") # 通过标准输入接收用户的鹅指令
       resp = agent.run_sync(user_input,
                             message_history=history) # 将用户输入和历史记录直接传给Agent
       history = list(resp.all_messages()) # 保留聊天记录
       print(resp.output)  # 打印AI的返回结果


if __name__ == "__main__":
   main()

tools.py

python 复制代码
from pathlib import Path
import os

base_dir = Path("./test")

# 读文件
def read_file(name: str) -> str:
    """Return file content. If not exist, return error message.
    """
    print(f"(read_file {name})")
    try:
        with open(base_dir / name, "r") as f:
            content = f.read()
        return content
    except Exception as e:
        return f"An error occurred: {e}"
# 列目录
def list_files() -> list[str]:
    print("(list_file)")
    file_list = []
    for item in base_dir.rglob("*"):
        if item.is_file():
            file_list.append(str(item.relative_to(base_dir)))
    return file_list
# 改文件名
def rename_file(name: str, new_name: str) -> str:
    print(f"(rename_file {name} -> {new_name})")
    try:
        new_path = base_dir / new_name
        if not str(new_path).startswith(str(base_dir)):
            return "Error: new_name is outside base_dir."

        os.makedirs(new_path.parent, exist_ok=True)
        os.rename(base_dir / name, new_path)
        return f"File '{name}' successfully renamed to '{new_name}'."
    except Exception as e:
        return f"An error occurred: {e}"
相关推荐
刘大大Leo1 小时前
GPT-5.3-Codex 炸了:第一个「自己造自己」的 AI 编程模型,到底意味着什么?
人工智能·gpt
小镇敲码人1 小时前
剖析CANN框架中Samples仓库:从示例到实战的AI开发指南
c++·人工智能·python·华为·acl·cann
摘星编程1 小时前
CANN ops-nn Pooling算子解读:CNN模型下采样与特征提取的核心
人工智能·神经网络·cnn
程序员清洒1 小时前
CANN模型安全:从对抗防御到隐私保护的全栈安全实战
人工智能·深度学习·安全
island13141 小时前
CANN ops-nn 算子库深度解析:神经网络计算引擎的底层架构、硬件映射与融合优化机制
人工智能·神经网络·架构
小白|1 小时前
CANN与实时音视频AI:构建低延迟智能通信系统的全栈实践
人工智能·实时音视频
Kiyra1 小时前
作为后端开发你不得不知的 AI 知识——Prompt(提示词)
人工智能·prompt
艾莉丝努力练剑1 小时前
实时视频流处理:利用ops-cv构建高性能CV应用
人工智能·cann
程序猿追1 小时前
深度解析CANN ops-nn仓库 神经网络算子的性能优化与实践
人工智能·神经网络·性能优化
User_芊芊君子1 小时前
CANN_PTO_ISA虚拟指令集全解析打造跨平台高性能计算的抽象层
人工智能·深度学习·神经网络