从零开始:用Python和Gemini 3四步搭建你自己的AI Agent

简介: AI Agent并非玄学,核心仅为“循环 + 大模型 + 工具函数”。本文教你用Gemini 3从零搭建能读写文件、执行指令的命令行助手,拆解其“观察-思考-行动”循环机制,揭示智能体背后的简洁本质。

很多人第一次看到 AI Agent 自己编辑文件、跑代码、修 bug,还能一直运行下去的时候,都觉得挺神奇。其实远没有想象中那么复杂。这里没什么秘密算法,也没有什么"智能体大脑"这种玄学概念。

AI Agent核心就三件事:循环 + LLM + 工具函数

如果你会写个

while True

循环?那基本就算成功一半了。

这篇文章会完整展示怎么用 Gemini 3 搭一个真正能用的 Agent:从最基础的 API 调用,到一个能读写文件、理解需求的命令行助手。

Agent 到底是什么

传统程序就是流程图那一套:步骤 A → 步骤 B → 步骤 C → 结束。

而Agent 不一样,它会根据当前状况决定下一步干什么。可以理解成围绕 LLM 搭的一个小系统,比如说:

  • 规划任务
  • 执行操作
  • 根据结果调整
  • 循环往复直到搞定

所以不是写死的脚本,更像是个会思考的循环。

不管多复杂的 Agent,都逃不开这四个部分:

1、模型 负责思考

这里用的是 Gemini 3 Pro。它可以分析用户需求,决定接下来该做什么。

2、工具 负责执行

就是一堆函数:读文件、列目录、发邮件、调 API...想加什么加什么。

3、上下文工作记忆

模型当前能看到的所有信息,怎么管理这块内容,业内叫 Context Engineering

4、循环 运转机制

观察 → 思考 → 行动 → 重复,一直到任务完成。

就这么四块,没别的了。

循环的运行逻辑

几乎所有 Agent 都是这个流程:

先把可用的工具描述给模型看,然后把用户请求和工具定义一起发给模型。模型会做决策:要么直接回复,要么调用某个工具并传参数。

但是你要写代码负责在 Python 里执行这个工具。

执行完把结果喂回给 Gemini。

模型拿到新信息后继续判断下一步。

就这样循环,直到模型觉得任务完成了。

下面我们开始写:

第一步:基础聊天机器人

先写个 Gemini 3 API 的简单封装 ,其实就是个能记住对话的类。

 from google import genai  
from google.genai import types  

class Agent:  
    def __init__(self, model: str):  
        self.model = model  
        self.client = genai.Client()  
        self.contents = []  

    def run(self, contents: str):  
        self.contents.append({"role": "user", "parts": [{"text": contents}]})  

        response = self.client.models.generate_content(  
            model=self.model,  
            contents=self.contents  
        )  

        self.contents.append(response.candidates[0].content)  
        return response  

agent = Agent(model="gemini-3-pro-preview")  

response1 = agent.run(  
    "Hello, what are the top 3 cities in Germany to visit? Only return the names."  
)  
 print(response1.text)

上面代码能跑,但是就是个聊天机器人。它啥也干不了,因为没有"手"。

第二步:加入工具函数

工具其实就是 Python 函数 + 一段 JSON schema 描述。描述是给 Gemini 看的,让它知道这个函数能干啥。

这里加三个简单的:

  • read_file - 读文件
  • write_file - 写文件
  • list_dir - 列目录

先写定义:

 read_file_definition = {  
    "name": "read_file",  
    "description": "Reads a file and returns its contents.",  
    "parameters": {  
        "type": "object",  
        "properties": {  
            "file_path": {"type": "string"}  
        },  
        "required": ["file_path"],  
    },  
}  

list_dir_definition = {  
    "name": "list_dir",  
    "description": "Lists the files in a directory.",  
    "parameters": {  
        "type": "object",  
        "properties": {  
            "directory_path": {"type": "string"}  
        },  
        "required": ["directory_path"],  
    },  
}  

write_file_definition = {  
    "name": "write_file",  
    "description": "Writes contents to a file.",  
    "parameters": {  
        "type": "object",  
        "properties": {  
            "file_path": {"type": "string"},  
            "contents": {"type": "string"},  
        },  
        "required": ["file_path", "contents"],  
    },  
 }

然后是实际的 Python 实现:

 def read_file(file_path: str) -> dict:  
    with open(file_path, "r") as f:  
        return f.read()  

def write_file(file_path: str, contents: str) -> bool:  
    with open(file_path, "w") as f:  
        f.write(contents)  
    return True  

def list_dir(directory_path: str) -> list[str]:  
     return os.listdir(directory_path)

打包一下就搞定了:

 file_tools = {  
     "read_file": {"definition": read_file_definition, "function": read_file},  
     "write_file": {"definition": write_file_definition, "function": write_file},  
     "list_dir": {"definition": list_dir_definition, "function": list_dir},  
 }

第三步:真正的 Agent

现在把 Agent 类扩展一下,让它能:

  • 识别工具调用
  • 在 Python 里执行对应的函数
  • 把结果传回 Gemini
  • 继续循环直到完成
 class Agent:  
    def __init__(self, model: str, tools: dict,   
                 system_instruction="You are a helpful assistant."):  
        self.model = model  
        self.client = genai.Client()  
        self.contents = []  
        self.tools = tools  
        self.system_instruction = system_instruction  

    def run(self, contents):  
        # Add user input to history  
        if isinstance(contents, list):  
            self.contents.append({"role": "user", "parts": contents})  
        else:  
            self.contents.append({"role": "user", "parts": [{"text": contents}]})  

        config = types.GenerateContentConfig(  
            system_instruction=self.system_instruction,  
            tools=[types.Tool(  
                function_declarations=[  
                    tool["definition"] for tool in self.tools.values()  
                ]  
            )],  
        )  

        response = self.client.models.generate_content(  
            model=self.model,  
            contents=self.contents,  
            config=config  
        )  

        # Save model output  
        self.contents.append(response.candidates[0].content)  

        # If model wants to call tools  
        if response.function_calls:  
            functions_response_parts = []  

            for tool_call in response.function_calls:  
                print(f"[Function Call] {tool_call}")  

                if tool_call.name in self.tools:  
                    result = {"result": self.tools[tool_call.name]["function"](**tool_call.args)}  
                else:  
                    result = {"error": "Tool not found"}  

                print(f"[Function Response] {result}")  

                functions_response_parts.append(  
                    {"functionResponse": {"name": tool_call.name, "response": result}}  
                )  

            # Feed tool results back to the model  
            return self.run(functions_response_parts)  

         return response

这样就可以跑一下试试了:

 agent = Agent(  
    model="gemini-3-pro-preview",  
    tools=file_tools,  
    system_instruction="You are a helpful Coding Assistant. Respond like Linus Torvalds."  
)  

response = agent.run("Can you list my files in the current directory?")  
 print(response.text)

如果没问题,Gemini 会调工具,拿到结果,然后给出最终回复。

到这一步,一个能用的 Agent 就搭好了。

第四步:包装成命令行工具

最后我们在再套个输入循环就行:

 agent = Agent(  
    model="gemini-3-pro-preview",  
    tools=file_tools,  
    system_instruction="You are a helpful Coding Assistant. Respond like Linus Torvalds."  
)  

print("Agent ready. Type something (or 'exit').")  
while True:  
    user_input = input("You: ")  
    if user_input.lower() in ['exit', 'quit']:  
        break  

    response = agent.run(user_input)  
     print("Linus:", response.text, "\n")

代码很少但是效果已经相当不错了。

总结

搭 Agent 一开始看着挺唬人,但理解了结构之后,会发现简单得有点无聊。往简单了说,它就是个循环。一个里面跑着聪明模型的循环。明白这点之后,你就能造出看起来"有生命"的 Agent 了。

如果想继续扩展的话,可以加这些:

网络搜索、数据库查询、执行 shell 命令、调用云服务、长期记忆、工作流编排、任务调度、多步规划...

但不管怎么加,底层还是那个简单结构:

观察 → 思考 → 行动 → 重复

https://avoid.overfit.cn/post/67cef1690eb14d2fb3ecc0ff7bdf91f8

这就是现代 Agent 的核心。

目录
相关文章
|
5月前
|
人工智能 安全 机器人
智能体来了:从 0 到 1 搭建高效 AI Agent 工作流全指南
2026 年,大模型应用已进入“智能体工作流(Agentic Workflow)”的深水区。单次提示词输出已无法满足复杂的商业需求。本文将深度解析如何从底层架构到生产环境,从 0 到 1 搭建一个具备自我进化能力的智能体工作流。本文旨在为开发者提供一份高权重的技术参考指南。
6770 2
|
7月前
|
机器学习/深度学习 人工智能 缓存
让AI评测AI:构建智能客服的自动化运营Agent体系
大模型推动客服智能化演进,从规则引擎到RAG,再到AI原生智能体。通过构建“评估-诊断-优化”闭环的运营Agent,实现对话效果自动化评测与持续优化,显著提升服务质量和效率。
3355 86
让AI评测AI:构建智能客服的自动化运营Agent体系
|
4月前
|
人工智能 NoSQL Redis
LangGraph 入门:用图结构构建你的第一个多智能体工作流
LangGraph 是面向多智能体系统的图编排框架,以有向状态图替代线性链式调用。通过节点(智能体)、边(条件/静态跳转)和类型化共享状态三者解耦,天然支持分支、循环、并行与汇合;内置检查点、原子状态更新与Reducer机制,保障一致性、可调试性与容错恢复能力。
3385 1
|
4月前
|
人工智能 数据可视化 搜索推荐
AI智能体实战指南:6大工具构建你的自动化工作流引擎
本文介绍2024年六大AI智能体工具:测试自动化(Playwright/Appium)、代码生成(Cursor/OpenCode)、AI工作流(ClawdBot/Dify/n8n)、短视频创作(FFmpeg/MoviePy)等,助开发者构建端到端自动化工作流,释放创造力。
|
5月前
|
传感器 人工智能 架构师
2026实战蓝图:AI Agent全栈开发培训流程与AI Agent职业路线进阶指南
摘要: 2026年,大模型正式进入“行动元年”。AI Agent(智能体)已从的对话接口转变为具备自主逻辑、环境感知与复杂协作能力的数字员工。本文将深度拆解从LLM向Agent覆盖的技术基础逻辑,规划从初级开发者到Agent架构师的职业路径,并提供一套简单的工程化的培训方法论。
4655 3
|
5月前
|
人工智能 供应链 监控
2026 AI元年核心赛道:AI智能体,如何重构企业工作流?
2026年作为AI元年,AI智能体已从技术概念走向企业实操,成为重构企业工作流、破解传统协同壁垒与效能瓶颈的核心力量。不同于传统自动化工具,AI智能体凭借自主决策、多任务协同、持续学习的能力,以“人机协同、效能倍增”为核心逻辑,依托基础大模型、智能编排框架、工具生态三大技术支柱,在营销、财务、客服、供应链四大核心场景实现低成本落地。本文结合企业实操经验,梳理AI智能体重构工作流的底层逻辑与“试点-优化-规模化”三步落地路径,为各规模企业提供可参考的实操指南,助力企业通过AI智能体实现降本增效,抢占AI时代核心竞争力。​
|
7月前
|
人工智能 JSON 缓存
CrewAI 上手攻略:多 Agent 自动化处理复杂任务,让 AI 像员工一样分工协作
CrewAI 是一个基于 Python 的自主 AI 智能体编排框架,可构建“虚拟团队”协同完成复杂任务。通过定义角色明确的 Agents、任务流 Tasks、协作流程 Processes 及可用工具 Tools,实现研究、写作、开发等多环节自动化。适用于长链条工作流,如研报生成、竞品分析、软件开发等,支持异步执行、人工介入与结构化输出,集成主流大模型与工具生态,是处理复杂知识型任务的高效选择。(238 字)
1341 0
CrewAI 上手攻略:多 Agent 自动化处理复杂任务,让 AI 像员工一样分工协作
|
2月前
|
人工智能 运维 Serverless
从0到1:3分钟搭建你的第一个企业级AI Agent实战指南
本文分享如何用阿里云函数计算AgentRun,零运维、低成本地从零搭建企业级AI Agent:支持模板开箱即用、高代码自定义、多Agent协同,并已落地吉利、森马等真实场景。(239字)
1411 0
|
5月前
|
存储 人工智能 数据库
到底什么是AI Agent?
Agent是具备感知、决策与行动能力的智能体,通过大模型(LLM)结合记忆(Memory)和工具(Tools)调用,实现自主规划与执行任务,如小爱同学自动点餐。其核心为:LLM + Memory + Tools + Planning。
3529 7

热门文章

最新文章