<cite id="ffb66"></cite><cite id="ffb66"><track id="ffb66"></track></cite>
      <legend id="ffb66"><li id="ffb66"></li></legend>
      色婷婷久,激情色播,久久久无码专区,亚洲中文字幕av,国产成人A片,av无码免费,精品久久国产,99视频精品3
      網易首頁 > 網易號 > 正文 申請入駐

      用 Gemini 3 構建 AI Agent:從循環到智能體的實踐指南

      0
      分享至


      很多人第一次看到 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 命令、調用云服務、長期記憶、工作流編排、任務調度、多步規劃...

      但不管怎么加,底層還是那個簡單結構:

      觀察 → 思考 → 行動 → 重復

      這就是現代 Agent 的核心。

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

      特別聲明:以上內容(如有圖片或視頻亦包括在內)為自媒體平臺“網易號”用戶上傳并發布,本平臺僅提供信息存儲服務。

      Notice: The content above (including the pictures and videos if any) is uploaded and posted by a user of NetEase Hao, which is a social media platform and only provides information storage services.

      相關推薦
      熱點推薦
      驚人一致!99%的女人玩夠男人后,都會默契地做出這3種行為。

      驚人一致!99%的女人玩夠男人后,都會默契地做出這3種行為。

      荷蘭豆愛健康
      2026-03-07 12:19:26
      終身追殺令生效,什葉派終極殺招,特朗普與內塔尼亞胡無處可逃

      終身追殺令生效,什葉派終極殺招,特朗普與內塔尼亞胡無處可逃

      健身狂人
      2026-03-06 17:28:14
      哈登喜迎好幫手,騎士這奪冠拼圖終于齊了

      哈登喜迎好幫手,騎士這奪冠拼圖終于齊了

      章蠞戶外
      2026-03-07 11:38:45
      這老師真是絕代美人啊!

      這老師真是絕代美人??!

      東方不敗然多多
      2026-03-01 01:09:31
      妹子給貓定做項鏈,發貓名卻被判定為違禁詞?一看貓名:真的很少站平臺

      妹子給貓定做項鏈,發貓名卻被判定為違禁詞?一看貓名:真的很少站平臺

      拜見喵主子
      2026-03-06 12:23:47
      56歲大媽心梗離世,醫生:吃他汀時除了牛奶,這6種食物盡量少碰

      56歲大媽心梗離世,醫生:吃他汀時除了牛奶,這6種食物盡量少碰

      岐黃傳人孫大夫
      2026-02-28 22:15:03
      特朗普拒絕收拾爛攤子?對以色列下達最后通牒,24小時內必須執行

      特朗普拒絕收拾爛攤子?對以色列下達最后通牒,24小時內必須執行

      咣當地球
      2026-03-06 20:27:02
      中國AI算力暗戰:字節阿里押注英偉達,訊飛全國產,百度走雙軌

      中國AI算力暗戰:字節阿里押注英偉達,訊飛全國產,百度走雙軌

      劉曠
      2026-03-06 08:53:37
      中東沒結束,亞太又出問題?朝鮮突發導彈,特朗普收到一封挑戰書

      中東沒結束,亞太又出問題?朝鮮突發導彈,特朗普收到一封挑戰書

      阿校談史
      2026-03-07 11:44:53
      《鏢人》票房超12億,打破14項紀錄,虧損超2億

      《鏢人》票房超12億,打破14項紀錄,虧損超2億

      影視高原說
      2026-03-06 07:03:59
      曾經全球僅存1株!2016年北京又發現1株快死的,現在怎樣了?

      曾經全球僅存1株!2016年北京又發現1株快死的,現在怎樣了?

      萬象硬核本尊
      2026-03-06 14:11:42
      全國人大代表黃勇平:不要讓做好研究的人,天天把時間花在申請經費上

      全國人大代表黃勇平:不要讓做好研究的人,天天把時間花在申請經費上

      上觀新聞
      2026-03-06 22:37:05
      新加坡急了,外長幾乎是拍著桌子,讓中國“尊重”馬六甲的地位。

      新加坡急了,外長幾乎是拍著桌子,讓中國“尊重”馬六甲的地位。

      南權先生
      2026-01-26 15:41:26
      山西王閻錫山的妹妹,沒來得及跟哥哥逃到臺灣,她的結局如何?

      山西王閻錫山的妹妹,沒來得及跟哥哥逃到臺灣,她的結局如何?

      老范談史
      2026-03-03 17:43:41
      倒閉注銷!天津這家33年老清真館,也黃了!?

      倒閉注銷!天津這家33年老清真館,也黃了!?

      天津族
      2026-03-07 07:35:06
      再讀《穆斯林的葬禮》,對茅盾文學獎的信任崩塌了!

      再讀《穆斯林的葬禮》,對茅盾文學獎的信任崩塌了!

      難得君
      2026-03-06 13:43:16
      96年王光美為沒錢憂愁不已,忽然看到一只象牙筆筒:它也能換錢?

      96年王光美為沒錢憂愁不已,忽然看到一只象牙筆筒:它也能換錢?

      談古論今歷史有道
      2026-03-07 13:05:03
      回顧70歲老漢慘死家中,胸口紙條寫著:你該死讓你下輩子再玩女人

      回顧70歲老漢慘死家中,胸口紙條寫著:你該死讓你下輩子再玩女人

      談史論天地
      2026-03-06 15:17:43
      補時“50分鐘” 皇馬94分鐘絕殺:丑陋2-1止住2連敗 43歲少帥命硬

      補時“50分鐘” 皇馬94分鐘絕殺:丑陋2-1止住2連敗 43歲少帥命硬

      風過鄉
      2026-03-07 06:31:03
      俄媒:蘇萊曼尼繼任者是內鬼,確認哈梅內伊位置,會沒開完就溜了

      俄媒:蘇萊曼尼繼任者是內鬼,確認哈梅內伊位置,會沒開完就溜了

      梁訊
      2026-03-07 04:17:49
      2026-03-07 13:39:00
      deephub incentive-icons
      deephub
      CV NLP和數據挖掘知識
      1940文章數 1456關注度
      往期回顧 全部

      科技要聞

      OpenClaw爆火,六位"養蝦人"自述與AI共生

      頭條要聞

      特朗普突然放話"先解決伊朗后解決古巴" 梅西聽懵了

      頭條要聞

      特朗普突然放話"先解決伊朗后解決古巴" 梅西聽懵了

      體育要聞

      塔圖姆歸來:凱爾特人的春之綠

      娛樂要聞

      周杰倫田馥甄的“JH戀” 被扒得底朝天

      財經要聞

      針對"不敢休、不讓休"怪圈 國家出手了

      汽車要聞

      逃離ICU,上汽通用“止血”企穩

      態度原創

      本地
      數碼
      時尚
      公開課
      軍事航空

      本地新聞

      食味印象|一口入魂!康樂烤肉串起千年絲路香

      數碼要聞

      蘋果M5 Pro芯片GeekBench跑分曝光:多核破2.8萬

      這些才是適合普通人的穿搭!搭配腰帶、多穿牛仔褲,簡單舒適

      公開課

      李玫瑾:為什么性格比能力更重要?

      軍事要聞

      伊朗:使用無人機擊中美軍"林肯"號航母

      無障礙瀏覽 進入關懷版