搭建一个简单的Agent

准备

本案例使用deepseek,登录deepseek官网,登录账号,充值几块钱,然后创建Api key

可以创建虚拟环境,python版本最好是3.12,以下是文件目录。test文件夹中,放一些txt文件做测试,main.py就是充当agent,tools.py是自定义工具(函数),大模型就是通过调用这些工具帮你完成需求。

大致流程就是,我写好工具,创建一个agent(一段程序),在agent中注册好我创建的工具,同时调用deepseek(作为我的私人程序员)。之后,我向agent发出需求,agent将需求传递给deepseek,deepseek分析出完成这个需求,需要使用哪些工具,返回给agent,agent根据指示再去调用工具,工具执行完,将结果返回给agent,agent再将结果返回给deepseek,然后deepseek给出最终答案,返回给agent,agent返回给用户。

工具

这里,我们就指定了只对 test文件夹进行操作,有 列出文件夹中所有文件名称、读取文件内容、重命名文件、创建文件的四个工具。

复制代码
import os

test_path = os.path.join(os.path.dirname(os.path.abspath(__file__)),'test')


print(test_path)
def list_files() -> list[str]:
    """
    列出 test 文件夹中所有文件名称,返回列表(相对路径)
    """
    file_list = []
    for root, dirs, files in os.walk(test_path):
        for file in files:
            # 获取相对路径
            rel_path = os.path.relpath(os.path.join(root, file), test_path)
            file_list.append(rel_path)
    return file_list

print(list_files())

def read_file(name: str) -> str:
    """
    读取test文件夹下,某一文件内容
    """
    print(f"(read_file {name})")
    try:
        with open(os.path.join(test_path,name), "r") as f:
            content = f.read()
        return content
    except Exception as e:
        return f"An error occurred: {e}"



def rename_file(name: str, new_name: str) -> str:
    """
    重命名 test 文件夹下的文件
    """
    print(f"(rename_file {name} -> {new_name})")
    try:
        old_path = os.path.join(test_path, name)
        new_path = os.path.join(test_path, new_name)

        # 检查 new_path 是否在 test_path 内
        if not os.path.abspath(new_path).startswith(os.path.abspath(test_path)):
            return "Error: new_name is outside test_path."

        # 创建父目录
        os.makedirs(os.path.dirname(new_path), exist_ok=True)

        # 执行重命名
        os.rename(old_path, new_path)
        return f"File '{name}' successfully renamed to '{new_name}'."

    except Exception as e:
        return f"An error occurred: {e}"
    
def create_file(name: str, content: str = "") -> str:
    """
    在 test 文件夹下创建文件,并写入内容
    """
    print(f"(create_file {name})")
    try:
        file_path = os.path.join(test_path, name)

        # 检查文件是否在 test_path 内
        if not os.path.abspath(file_path).startswith(os.path.abspath(test_path)):
            return "Error: file path is outside test_path."

        # 创建父目录(如果有子目录的话)
        os.makedirs(os.path.dirname(file_path), exist_ok=True)

        # 写入内容
        with open(file_path, "w", encoding="utf-8") as f:
            f.write(content)

        return f"File '{name}' successfully created."

    except Exception as e:
        return f"An error occurred: {e}"

agent

复制代码
pip install pydantic-ai

如果安装完成后,出现  pydantic-core 不存在 的错误
pip install --force-reinstall --no-cache-dir --only-binary=:all: pydantic-core -i https://pypi.org/simple

创建一个.env文件,里面写入

DEEPSEEK_API_KEY=你的deepseek api key 等号两边不要有空格,不要有引号

from pydantic_ai import Agent
from pydantic_ai.models.openai import OpenAIModel
from pydantic_ai.providers.openai import OpenAIProvider
import tools
from dotenv import load_dotenv
import os
load_dotenv()#读取env文件中的变量到环境变量中


#使用deepseek模型
model = OpenAIModel(
                    "deepseek-chat",
                    provider=OpenAIProvider(
                        api_key=os.getenv('DEEPSEEK_API_KEY'), # 从环境变量加载API密钥
                        base_url="https://api.deepseek.com"
                    )
                )
agent = Agent(
                model,
                system_prompt='你是我的windows系统管理大师' ,#设定大模型其角色
                tools=[                 #给agent注册工具
                tools.list_files,
                tools.rename_file,
                tools.read_file,
                tools.create_file,
                ] 
            )

def main():
    history = []
    while True:
        user_input = input("Input: ")
        resp = agent.run_sync(user_input,
                              message_history=history)#记住上下文
        history = list(resp.all_messages())
        print(resp.output)


if __name__ == "__main__":
    main()

执行结果,此时的agent就像一个你自己雇佣的程序员一样,可以对test文件夹执行你指定工具的所有功能

相关推荐
九章云极AladdinEdu7 小时前
超参数自动化调优指南:Optuna vs. Ray Tune 对比评测
运维·人工智能·深度学习·ai·自动化·gpu算力
CoderJia程序员甲14 小时前
GitHub 热榜项目 - 日榜(2025-09-13)
ai·开源·大模型·github·ai教程
AI大模型14 小时前
RAG 真的不聪明?其实它只是缺了这一步……
程序员·llm·agent
大模型教程14 小时前
普通人如何借助 Agentic RAG 打造全智能化电商客服与客户沟通体系
程序员·llm·agent
蒋星熠17 小时前
如何在Anaconda中配置你的CUDA & Pytorch & cuNN环境(2025最新教程)
开发语言·人工智能·pytorch·python·深度学习·机器学习·ai
Code_流苏18 小时前
AI热点周报(9.7~9.13):阿里Qwen3-Next震撼发布、Claude 增强记忆与服务抖动、OpenAI 聚焦模型规范化...
人工智能·gpt·ai·openai·claude·qwen3-next·架构创新
聚客AI18 小时前
🚫万能Agent兜底:当规划缺失工具时,AI如何自救
人工智能·llm·agent
@鱼香肉丝没有鱼18 小时前
分布式推理与量化部署
ai·大模型·推理部署
程序员鱼皮19 小时前
AI 应用开发,不就是调个接口么?
计算机·ai·程序员·互联网·编程·网站
安思派Anspire1 天前
从 ETL 到 ELT 再到 EAI:AI 如何重塑数据处理
aigc·openai·agent