亚洲国产日韩欧美一区二区三区,精品亚洲国产成人av在线,国产99视频精品免视看7,99国产精品久久久久久久成人热,欧美日韩亚洲国产综合乱

首頁(yè) 後端開(kāi)發(fā) Python教學(xué) Agent工具開(kāi)髮指南:從設(shè)計(jì)到最佳化

Agent工具開(kāi)髮指南:從設(shè)計(jì)到最佳化

Nov 23, 2024 am 05:53 AM

Agent Tool Development Guide: From Design to Optimization

一、簡(jiǎn)介

想像一下你正在組裝一個(gè)超級(jí)智慧的機(jī)器人管家(特務(wù))。這個(gè)機(jī)器人需要各種工具來(lái)幫助你完成任務(wù)──就像哆啦A夢(mèng)的4D口袋一樣。本文將教您如何創(chuàng)造這些強(qiáng)大的工具,讓您的AI管家更加得力和有效率。

2. 兩個(gè)核心工具設(shè)計(jì)模式

2.1 同步工具:即時(shí)回應(yīng)模式

考慮使用自助咖啡機(jī):

  1. 插入硬幣並按下「美式咖啡」按鈕
  2. 稍等幾秒
  3. 咖啡流出,可以喝了

這是典型的同步工具模式。代理呼叫該工具並等待立即結(jié)果 - 快速而簡(jiǎn)單。

class WeatherTool(BaseTool):
    """Weather Query Tool - Synchronous Mode"""
    async def execute(self, city: str) -> dict:
        # Simple and direct like pressing a coffee machine button
        weather_data = await self.weather_api.get_current(city)
        return {
            "status": "success",
            "data": {
                "temperature": weather_data.temp,
                "humidity": weather_data.humidity,
                "description": weather_data.desc
            }
        }

用例:

  • 快速查詢(xún):天氣、匯率、簡(jiǎn)單計(jì)算
  • 簡(jiǎn)單的操作:傳送訊息、切換控制
  • 即時(shí)回饋:驗(yàn)證碼查詢(xún)、餘額查詢(xún)

2.2 非同步工具:任務(wù)追蹤模式

想像一下透過(guò)外帶應(yīng)用程式訂購(gòu)食物:

  1. 下單後,APP會(huì)給你一個(gè)訂單號(hào)碼
  2. 您可以隨時(shí)查看訂單狀態(tài)
  3. 配送完成後APP會(huì)通知您

這就是非同步工具的工作原理,非常適合需要較長(zhǎng)時(shí)間處理的任務(wù)。

class DocumentAnalysisTool(BaseTool):
    """Document Analysis Tool - Asynchronous Mode"""

    async def start_task(self, file_path: str) -> str:
        # Like placing a food delivery order, returns a task ID
        task_id = str(uuid.uuid4())
        await self.task_queue.put({
            "task_id": task_id,
            "file_path": file_path,
            "status": "processing"
        })
        return task_id

    async def get_status(self, task_id: str) -> dict:
        # Like checking food delivery status
        task = await self.task_store.get(task_id)
        return {
            "task_id": task_id,
            "status": task["status"],
            "progress": task.get("progress", 0),
            "result": task.get("result", None)
        }

用例:

  • 耗時(shí)操作:大檔案處理、資料分析
  • 多步驟任務(wù):影片渲染、報(bào)表產(chǎn)生
  • 需要進(jìn)度追蹤:模型訓(xùn)練、批次

3. 工具介面標(biāo)準(zhǔn)化:建立通用規(guī)範(fàn)

就像所有電器都遵循統(tǒng)一的插座標(biāo)準(zhǔn)一樣,我們的工具介面也需要標(biāo)準(zhǔn)化。這可確保所有工具與代理商完美搭配。

3.1 工具說(shuō)明規(guī)格

想像一下寫(xiě)一份產(chǎn)品手冊(cè),你需要清楚告訴使用者:

  • 該工具的作用
  • 需要什麼參數(shù)
  • 會(huì)回傳什麼結(jié)果
from pydantic import BaseModel, Field

class ToolSchema(BaseModel):
    """Tool Manual Template"""
    name: str = Field(..., description="Tool name")
    description: str = Field(..., description="Tool purpose description")
    parameters: dict = Field(..., description="Required parameters")
    required: List[str] = Field(default_factory=list, description="Required parameters")

    class Config:
        schema_extra = {
            "example": {
                "name": "Weather Query",
                "description": "Query weather information for specified city",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "city": {
                            "type": "string",
                            "description": "City name"
                        }
                    }
                },
                "required": ["city"]
            }
        }

3.2 統(tǒng)一基類(lèi)

就像所有電器都需要電源開(kāi)關(guān)和電源介面一樣,所有工具都需要遵循基本規(guī)格:

class BaseTool(ABC):
    """Base template for all tools"""

    @abstractmethod
    def get_schema(self) -> ToolSchema:
        """Tool manual"""
        pass

    def validate_input(self, params: Dict) -> Dict:
        """Parameter check, like a fuse in electrical appliances"""
        return ToolSchema(**params).dict()

    @abstractmethod
    async def execute(self, **kwargs) -> Dict:
        """Actual functionality execution"""
        pass

4. 錯(cuò)誤處理:讓工具更可靠

就像家用電器需要防水、防震、過(guò)載保護(hù)一樣,工具也需要完善的保護(hù)機(jī)制。

4.1 錯(cuò)誤分類(lèi)及處理

想像一下處理快遞:

  • 位址錯(cuò)誤→參數(shù)錯(cuò)誤
  • 系統(tǒng)維護(hù)→服務(wù)暫時(shí)無(wú)法使用
  • 快遞太忙→需要限制速率並重試
class WeatherTool(BaseTool):
    """Weather Query Tool - Synchronous Mode"""
    async def execute(self, city: str) -> dict:
        # Simple and direct like pressing a coffee machine button
        weather_data = await self.weather_api.get_current(city)
        return {
            "status": "success",
            "data": {
                "temperature": weather_data.temp,
                "humidity": weather_data.humidity,
                "description": weather_data.desc
            }
        }

4.2 重試機(jī)制

就像第一次嘗試失敗時(shí)自動(dòng)安排第二次送貨:

class DocumentAnalysisTool(BaseTool):
    """Document Analysis Tool - Asynchronous Mode"""

    async def start_task(self, file_path: str) -> str:
        # Like placing a food delivery order, returns a task ID
        task_id = str(uuid.uuid4())
        await self.task_queue.put({
            "task_id": task_id,
            "file_path": file_path,
            "status": "processing"
        })
        return task_id

    async def get_status(self, task_id: str) -> dict:
        # Like checking food delivery status
        task = await self.task_store.get(task_id)
        return {
            "task_id": task_id,
            "status": task["status"],
            "progress": task.get("progress", 0),
            "result": task.get("result", None)
        }

5.性能優(yōu)化:讓工具更有效率

5.1 快取機(jī)制

就像便利商店一樣,將熱門(mén)商品放在顯眼的位置:

from pydantic import BaseModel, Field

class ToolSchema(BaseModel):
    """Tool Manual Template"""
    name: str = Field(..., description="Tool name")
    description: str = Field(..., description="Tool purpose description")
    parameters: dict = Field(..., description="Required parameters")
    required: List[str] = Field(default_factory=list, description="Required parameters")

    class Config:
        schema_extra = {
            "example": {
                "name": "Weather Query",
                "description": "Query weather information for specified city",
                "parameters": {
                    "type": "object",
                    "properties": {
                        "city": {
                            "type": "string",
                            "description": "City name"
                        }
                    }
                },
                "required": ["city"]
            }
        }

5.2 並發(fā)控制

像醫(yī)院的預(yù)約系統(tǒng),控制同時(shí)服務(wù)的數(shù)量:

class BaseTool(ABC):
    """Base template for all tools"""

    @abstractmethod
    def get_schema(self) -> ToolSchema:
        """Tool manual"""
        pass

    def validate_input(self, params: Dict) -> Dict:
        """Parameter check, like a fuse in electrical appliances"""
        return ToolSchema(**params).dict()

    @abstractmethod
    async def execute(self, **kwargs) -> Dict:
        """Actual functionality execution"""
        pass

6. 測(cè)試和文件:確保工具可靠性

6.1 單元測(cè)試

例如新產(chǎn)品上市前的品質(zhì)檢查:

class ToolError(Exception):
    """Tool error base class"""
    def __init__(self, message: str, error_code: str, retry_after: Optional[int] = None):
        self.message = message
        self.error_code = error_code
        self.retry_after = retry_after

@error_handler
async def execute(self, **kwargs):
    try:
        # Execute specific operation
        result = await self._do_work(**kwargs)
        return {"status": "success", "data": result}
    except ValidationError:
        # Parameter error, like wrong address
        return {"status": "error", "code": "INVALID_PARAMS"}
    except RateLimitError as e:
        # Need rate limiting, like courier too busy
        return {
            "status": "error", 
            "code": "RATE_LIMIT",
            "retry_after": e.retry_after
        }

6.2 文檔標(biāo)準(zhǔn)

就像寫(xiě)一份詳細(xì)且清楚的產(chǎn)品手冊(cè):

class RetryableTool(BaseTool):
    @retry(
        stop=stop_after_attempt(3),  # Maximum 3 retries
        wait=wait_exponential(multiplier=1, min=4, max=10)  # Increasing wait time
    )
    async def execute_with_retry(self, **kwargs):
        return await self.execute(**kwargs)

七、總結(jié)

開(kāi)發(fā)好的代理工具就像製作一個(gè)完美的工具箱:

  1. 正確的工具分類(lèi) - 同步/非同步各有其用途
  2. 標(biāo)準(zhǔn)化介面-方便統(tǒng)一管理
  3. 保護(hù)機(jī)制-處理各種異常
  4. 追求效率-需要時(shí)緩存,需要時(shí)限速
  5. 品質(zhì)焦點(diǎn) - 徹底的測(cè)試,清晰的文件

記?。汉玫墓ぞ呖梢宰?Agent 的效率加倍,而差的工具則會(huì)處處限制 Agent。

以上是Agent工具開(kāi)髮指南:從設(shè)計(jì)到最佳化的詳細(xì)內(nèi)容。更多資訊請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本網(wǎng)站聲明
本文內(nèi)容由網(wǎng)友自願(yuàn)投稿,版權(quán)歸原作者所有。本站不承擔(dān)相應(yīng)的法律責(zé)任。如發(fā)現(xiàn)涉嫌抄襲或侵權(quán)的內(nèi)容,請(qǐng)聯(lián)絡(luò)admin@php.cn

熱AI工具

Undress AI Tool

Undress AI Tool

免費(fèi)脫衣圖片

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅(qū)動(dòng)的應(yīng)用程序,用於創(chuàng)建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線(xiàn)上人工智慧工具。

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費(fèi)的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

記事本++7.3.1

記事本++7.3.1

好用且免費(fèi)的程式碼編輯器

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

禪工作室 13.0.1

禪工作室 13.0.1

強(qiáng)大的PHP整合開(kāi)發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺(jué)化網(wǎng)頁(yè)開(kāi)發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)程式碼編輯軟體(SublimeText3)

熱門(mén)話(huà)題

Laravel 教程
1597
29
PHP教程
1488
72
Python類(lèi)中的多態(tài)性 Python類(lèi)中的多態(tài)性 Jul 05, 2025 am 02:58 AM

多態(tài)是Python面向?qū)ο缶幊讨械暮诵母拍睿浮耙环N接口,多種實(shí)現(xiàn)”,允許統(tǒng)一處理不同類(lèi)型的對(duì)象。 1.多態(tài)通過(guò)方法重寫(xiě)實(shí)現(xiàn),子類(lèi)可重新定義父類(lèi)方法,如Animal類(lèi)的speak()方法在Dog和Cat子類(lèi)中有不同實(shí)現(xiàn)。 2.多態(tài)的實(shí)際用途包括簡(jiǎn)化代碼結(jié)構(gòu)、增強(qiáng)可擴(kuò)展性,例如圖形繪製程序中統(tǒng)一調(diào)用draw()方法,或遊戲開(kāi)發(fā)中處理不同角色的共同行為。 3.Python實(shí)現(xiàn)多態(tài)需滿(mǎn)足:父類(lèi)定義方法,子類(lèi)重寫(xiě)該方法,但不要求繼承同一父類(lèi),只要對(duì)象實(shí)現(xiàn)相同方法即可,這稱(chēng)為“鴨子類(lèi)型”。 4.注意事項(xiàng)包括保持方

解釋Python發(fā)電機(jī)和迭代器。 解釋Python發(fā)電機(jī)和迭代器。 Jul 05, 2025 am 02:55 AM

迭代器是實(shí)現(xiàn)__iter__()和__next__()方法的對(duì)象,生成器是簡(jiǎn)化版的迭代器,通過(guò)yield關(guān)鍵字自動(dòng)實(shí)現(xiàn)這些方法。 1.迭代器每次調(diào)用next()返回一個(gè)元素,無(wú)更多元素時(shí)拋出StopIteration異常。 2.生成器通過(guò)函數(shù)定義,使用yield按需生成數(shù)據(jù),節(jié)省內(nèi)存且支持無(wú)限序列。 3.處理已有集合時(shí)用迭代器,動(dòng)態(tài)生成大數(shù)據(jù)或需惰性求值時(shí)用生成器,如讀取大文件時(shí)逐行加載。注意:列表等可迭代對(duì)像不是迭代器,迭代器到盡頭後需重新創(chuàng)建,生成器只能遍歷一次。

如何處理Python中的API身份驗(yàn)證 如何處理Python中的API身份驗(yàn)證 Jul 13, 2025 am 02:22 AM

處理API認(rèn)證的關(guān)鍵在於理解並正確使用認(rèn)證方式。 1.APIKey是最簡(jiǎn)單的認(rèn)證方式,通常放在請(qǐng)求頭或URL參數(shù)中;2.BasicAuth使用用戶(hù)名和密碼進(jìn)行Base64編碼傳輸,適合內(nèi)部系統(tǒng);3.OAuth2需先通過(guò)client_id和client_secret獲取Token,再在請(qǐng)求頭中帶上BearerToken;4.為應(yīng)對(duì)Token過(guò)期,可封裝Token管理類(lèi)自動(dòng)刷新Token;總之,根據(jù)文檔選擇合適方式,並安全存儲(chǔ)密鑰信息是關(guān)鍵。

解釋Python斷言。 解釋Python斷言。 Jul 07, 2025 am 12:14 AM

Assert是Python用於調(diào)試的斷言工具,當(dāng)條件不滿(mǎn)足時(shí)拋出AssertionError。其語(yǔ)法為assert條件加可選錯(cuò)誤信息,適用於內(nèi)部邏輯驗(yàn)證如參數(shù)檢查、狀態(tài)確認(rèn)等,但不能用於安全或用戶(hù)輸入檢查,且應(yīng)配合清晰提示信息使用,僅限開(kāi)發(fā)階段輔助調(diào)試而非替代異常處理。

如何一次迭代兩個(gè)列表 如何一次迭代兩個(gè)列表 Jul 09, 2025 am 01:13 AM

在Python中同時(shí)遍歷兩個(gè)列表的常用方法是使用zip()函數(shù),它會(huì)按順序配對(duì)多個(gè)列表並以最短為準(zhǔn);若列表長(zhǎng)度不一致,可使用itertools.zip_longest()以最長(zhǎng)為準(zhǔn)並填充缺失值;結(jié)合enumerate()可同時(shí)獲取索引。 1.zip()簡(jiǎn)潔實(shí)用,適合成對(duì)數(shù)據(jù)迭代;2.zip_longest()處理不一致長(zhǎng)度時(shí)可填充默認(rèn)值;3.enumerate(zip())可在遍歷時(shí)獲取索引,滿(mǎn)足多種複雜場(chǎng)景需求。

什麼是Python迭代器? 什麼是Python迭代器? Jul 08, 2025 am 02:56 AM

Inpython,IteratorSareObjectSthallowloopingThroughCollectionsByImplementing_iter __()和__next __()。 1)iteratorsWiaTheIteratorProtocol,使用__ITER __()toreTurnterateratoratoranteratoratoranteratoratorAnterAnteratoratorant antheittheext__()

什麼是Python型提示? 什麼是Python型提示? Jul 07, 2025 am 02:55 AM

typeHintsInpyThonsolverbromblemboyofambiguityandPotentialBugSindyNamalytyCodeByallowingDevelopsosteSpecefectifyExpectedTypes.theyenhancereadability,enablellybugdetection,andimprovetool.typehintsupport.typehintsareadsareadsareadsareadsareadsareadsareadsareadsareaddedusidocolon(

Python Fastapi教程 Python Fastapi教程 Jul 12, 2025 am 02:42 AM

要使用Python創(chuàng)建現(xiàn)代高效的API,推薦使用FastAPI;其基於標(biāo)準(zhǔn)Python類(lèi)型提示,可自動(dòng)生成文檔,性能優(yōu)越。安裝FastAPI和ASGI服務(wù)器uvicorn後,即可編寫(xiě)接口代碼。通過(guò)定義路由、編寫(xiě)處理函數(shù)並返回?cái)?shù)據(jù),可以快速構(gòu)建API。 FastAPI支持多種HTTP方法,並提供自動(dòng)生成的SwaggerUI和ReDoc文檔系統(tǒng)。 URL參數(shù)可通過(guò)路徑定義捕獲,查詢(xún)參數(shù)則通過(guò)函數(shù)參數(shù)設(shè)置默認(rèn)值實(shí)現(xiàn)。合理使用Pydantic模型有助於提升開(kāi)發(fā)效率和準(zhǔn)確性。

See all articles