国产av日韩一区二区三区精品,成人性爱视频在线观看,国产,欧美,日韩,一区,www.成色av久久成人,2222eeee成人天堂

首頁(yè) 後端開(kāi)發(fā) Python教學(xué) LangGraph 狀態(tài)機(jī):管理生產(chǎn)中的複雜代理任務(wù)流

LangGraph 狀態(tài)機(jī):管理生產(chǎn)中的複雜代理任務(wù)流

Nov 24, 2024 am 03:37 AM

LangGraph State Machines: Managing Complex Agent Task Flows in Production

什麼是 LangGraph?

LangGraph是專(zhuān)為L(zhǎng)LM應(yīng)用程式設(shè)計(jì)的工作流程編排框架。其核心原則為:

  • 將複雜任務(wù)分解為狀態(tài)和轉(zhuǎn)換
  • 管理狀態(tài)轉(zhuǎn)換邏輯
  • 任務(wù)執(zhí)行過(guò)程中各種異常的處理

想想購(gòu)物:瀏覽→加入購(gòu)物車(chē)→結(jié)帳→??付款。 LangGraph 幫助我們有效地管理此類(lèi)工作流程。

核心概念

1. 國(guó)家

狀態(tài)就像任務(wù)執(zhí)行中的檢查點(diǎn):

from typing import TypedDict, List

class ShoppingState(TypedDict):
    # Current state
    current_step: str
    # Cart items
    cart_items: List[str]
    # Total amount
    total_amount: float
    # User input
    user_input: str

class ShoppingGraph(StateGraph):
    def __init__(self):
        super().__init__()

        # Define states
        self.add_node("browse", self.browse_products)
        self.add_node("add_to_cart", self.add_to_cart)
        self.add_node("checkout", self.checkout)
        self.add_node("payment", self.payment)

2. 狀態(tài)轉(zhuǎn)換

狀態(tài)轉(zhuǎn)換定義任務(wù)流程的「路線圖」:

class ShoppingController:
    def define_transitions(self):
        # Add transition rules
        self.graph.add_edge("browse", "add_to_cart")
        self.graph.add_edge("add_to_cart", "browse")
        self.graph.add_edge("add_to_cart", "checkout")
        self.graph.add_edge("checkout", "payment")

    def should_move_to_cart(self, state: ShoppingState) -> bool:
        """Determine if we should transition to cart state"""
        return "add to cart" in state["user_input"].lower()

3. 狀態(tài)持久化

為了確保系統(tǒng)的可靠性,我們需要持久化狀態(tài)資訊:

class StateManager:
    def __init__(self):
        self.redis_client = redis.Redis()

    def save_state(self, session_id: str, state: dict):
        """Save state to Redis"""
        self.redis_client.set(
            f"shopping_state:{session_id}",
            json.dumps(state),
            ex=3600  # 1 hour expiration
        )

    def load_state(self, session_id: str) -> dict:
        """Load state from Redis"""
        state_data = self.redis_client.get(f"shopping_state:{session_id}")
        return json.loads(state_data) if state_data else None

4. 錯(cuò)誤恢復(fù)機(jī)制

任何步驟都可能失敗,我們需要優(yōu)雅地處理這些情況:

class ErrorHandler:
    def __init__(self):
        self.max_retries = 3

    async def with_retry(self, func, state: dict):
        """Function execution with retry mechanism"""
        retries = 0
        while retries < self.max_retries:
            try:
                return await func(state)
            except Exception as e:
                retries += 1
                if retries == self.max_retries:
                    return self.handle_final_error(e, state)
                await self.handle_retry(e, state, retries)

    def handle_final_error(self, error, state: dict):
        """Handle final error"""
        # Save error state
        state["error"] = str(error)
        # Rollback to last stable state
        return self.rollback_to_last_stable_state(state)

現(xiàn)實(shí)範(fàn)例:智慧客戶服務(wù)系統(tǒng)

讓我們來(lái)看一個(gè)實(shí)際的例子-智慧客服系統(tǒng):

from langgraph.graph import StateGraph, State

class CustomerServiceState(TypedDict):
    conversation_history: List[str]
    current_intent: str
    user_info: dict
    resolved: bool

class CustomerServiceGraph(StateGraph):
    def __init__(self):
        super().__init__()

        # Initialize states
        self.add_node("greeting", self.greet_customer)
        self.add_node("understand_intent", self.analyze_intent)
        self.add_node("handle_query", self.process_query)
        self.add_node("confirm_resolution", self.check_resolution)

    async def greet_customer(self, state: State):
        """Greet customer"""
        response = await self.llm.generate(
            prompt=f"""
            Conversation history: {state['conversation_history']}
            Task: Generate appropriate greeting
            Requirements:
            1. Maintain professional friendliness
            2. Acknowledge returning customers
            3. Ask how to help
            """
        )
        state['conversation_history'].append(f"Assistant: {response}")
        return state

    async def analyze_intent(self, state: State):
        """Understand user intent"""
        response = await self.llm.generate(
            prompt=f"""
            Conversation history: {state['conversation_history']}
            Task: Analyze user intent
            Output format:
            {{
                "intent": "refund/inquiry/complaint/other",
                "confidence": 0.95,
                "details": "specific description"
            }}
            """
        )
        state['current_intent'] = json.loads(response)
        return state

用法

# Initialize system
graph = CustomerServiceGraph()
state_manager = StateManager()
error_handler = ErrorHandler()

async def handle_customer_query(user_id: str, message: str):
    # Load or create state
    state = state_manager.load_state(user_id) or {
        "conversation_history": [],
        "current_intent": None,
        "user_info": {},
        "resolved": False
    }

    # Add user message
    state["conversation_history"].append(f"User: {message}")

    # Execute state machine flow
    try:
        result = await graph.run(state)
        # Save state
        state_manager.save_state(user_id, result)
        return result["conversation_history"][-1]
    except Exception as e:
        return await error_handler.with_retry(
            graph.run,
            state
        )

最佳實(shí)踐

  1. 陳述設(shè)計(jì)原則

    • 保持狀態(tài)簡(jiǎn)單明了
    • 僅儲(chǔ)存必要的資訊
    • 考慮序列化要求
  2. 轉(zhuǎn)換邏輯最佳化

    • 使用條件轉(zhuǎn)換
    • 避免無(wú)限循環(huán)
    • 設(shè)定最大步數(shù)限制
  3. 錯(cuò)誤處理策略

    • 實(shí)作優(yōu)雅降級(jí)
    • 記錄詳細(xì)資料
    • 提供回滾機(jī)制
  4. 效能最佳化

    • 使用非同步操作
    • 實(shí)作狀態(tài)快取
    • 控制狀態(tài)大小

常見(jiàn)陷阱和解決方案

  1. 態(tài)爆炸

    • 問(wèn)題:狀態(tài)太多導(dǎo)致維護(hù)困難
    • 解決方案:合併相似的狀態(tài),使用狀態(tài)組合而不是創(chuàng)建新的
  2. 死鎖情況

    • 問(wèn)題:循環(huán)狀態(tài)轉(zhuǎn)換導(dǎo)致任務(wù)掛起
    • 解決方案:新增超時(shí)機(jī)制和強(qiáng)制退出條件
  3. 狀態(tài)一致性

    • 問(wèn)題:分散式環(huán)境狀態(tài)不一致
    • 解決方案:使用分散式鎖定和事務(wù)機(jī)制

概括

LangGraph 狀態(tài)機(jī)為管理複雜的 AI Agent 任務(wù)流程提供了強(qiáng)大的解決方案:

  • 清晰的任務(wù)流程管理
  • 可靠的狀態(tài)持久性
  • 全面的錯(cuò)誤處理
  • 靈活的擴(kuò)充性

以上是LangGraph 狀態(tài)機(jī):管理生產(chǎn)中的複雜代理任務(wù)流的詳細(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

用於從照片中去除衣服的線上人工智慧工具。

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)話題

Python類(lèi)中的多態(tài)性 Python類(lèi)中的多態(tài)性 Jul 05, 2025 am 02:58 AM

多態(tài)是Python面向?qū)ο缶幊讨械暮诵母拍?,指“一種接口,多種實(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)需滿足:父類(lèi)定義方法,子類(lèi)重寫(xiě)該方法,但不要求繼承同一父類(lèi),只要對(duì)象實(shí)現(xiàn)相同方法即可,這稱為“鴨子類(lèi)型”。 4.注意事項(xiàng)包括保持方

如何在Python中產(chǎn)生隨機(jī)字符串? 如何在Python中產(chǎn)生隨機(jī)字符串? Jun 21, 2025 am 01:02 AM

要生成隨機(jī)字符串,可以使用Python的random和string模塊組合。具體步驟為:1.導(dǎo)入random和string模塊;2.定義字符池如string.ascii_letters和string.digits;3.設(shè)定所需長(zhǎng)度;4.調(diào)用random.choices()生成字符串。例如代碼包括importrandom與importstring、設(shè)置length=10、characters=string.ascii_letters string.digits並執(zhí)行''.join(random.c

我如何寫(xiě)一個(gè)簡(jiǎn)單的'你好,世界!” Python的程序? 我如何寫(xiě)一個(gè)簡(jiǎn)單的'你好,世界!” Python的程序? Jun 24, 2025 am 12:45 AM

"Hello,World!"程序是用Python編寫(xiě)的最基礎(chǔ)示例,用於展示基本語(yǔ)法並驗(yàn)證開(kāi)發(fā)環(huán)境是否正確配置。 1.它通過(guò)一行代碼print("Hello,World!")實(shí)現(xiàn),運(yùn)行後會(huì)在控制臺(tái)輸出指定文本;2.運(yùn)行步驟包括安裝Python、使用文本編輯器編寫(xiě)代碼、保存為.py文件、在終端執(zhí)行該文件;3.常見(jiàn)錯(cuò)誤有遺漏括號(hào)或引號(hào)、誤用大寫(xiě)Print、未保存為.py格式以及運(yùn)行環(huán)境錯(cuò)誤;4.可選工具包括本地文本編輯器 終端、在線編輯器(如replit.com)

Python中的算法是什麼?為什麼它們很重要? Python中的算法是什麼?為什麼它們很重要? Jun 24, 2025 am 12:43 AM

AlgorithmsinPythonareessentialforefficientproblem-solvinginprogramming.Theyarestep-by-stepproceduresusedtosolvetaskslikesorting,searching,anddatamanipulation.Commontypesincludesortingalgorithmslikequicksort,searchingalgorithmslikebinarysearch,andgrap

python`@classmethod'裝飾師解釋了 python`@classmethod'裝飾師解釋了 Jul 04, 2025 am 03:26 AM

類(lèi)方法是Python中通過(guò)@classmethod裝飾器定義的方法,其第一個(gè)參數(shù)為類(lèi)本身(cls),用於訪問(wèn)或修改類(lèi)狀態(tài)。它可通過(guò)類(lèi)或?qū)嵗{(diào)用,影響的是整個(gè)類(lèi)而非特定實(shí)例;例如在Person類(lèi)中,show_count()方法統(tǒng)計(jì)創(chuàng)建的對(duì)像數(shù)量;定義類(lèi)方法時(shí)需使用@classmethod裝飾器並將首參命名為cls,如change_var(new_value)方法可修改類(lèi)變量;類(lèi)方法與實(shí)例方法(self參數(shù))、靜態(tài)方法(無(wú)自動(dòng)參數(shù))不同,適用於工廠方法、替代構(gòu)造函數(shù)及管理類(lèi)變量等場(chǎng)景;常見(jiàn)用途包括從

什麼是python的列表切片? 什麼是python的列表切片? Jun 29, 2025 am 02:15 AM

ListslicinginPythonextractsaportionofalistusingindices.1.Itusesthesyntaxlist[start:end:step],wherestartisinclusive,endisexclusive,andstepdefinestheinterval.2.Ifstartorendareomitted,Pythondefaultstothebeginningorendofthelist.3.Commonusesincludegetting

Python函數(shù)參數(shù)和參數(shù) Python函數(shù)參數(shù)和參數(shù) Jul 04, 2025 am 03:26 AM

參數(shù)(parameters)是定義函數(shù)時(shí)的佔(zhàn)位符,而傳參(arguments)是調(diào)用時(shí)傳入的具體值。 1.位置參數(shù)需按順序傳遞,順序錯(cuò)誤會(huì)導(dǎo)致結(jié)果錯(cuò)誤;2.關(guān)鍵字參數(shù)通過(guò)參數(shù)名指定,可改變順序且提高可讀性;3.默認(rèn)參數(shù)值在定義時(shí)賦值,避免重複代碼,但應(yīng)避免使用可變對(duì)像作為默認(rèn)值;4.args和*kwargs可處理不定數(shù)量的參數(shù),適用於通用接口或裝飾器,但應(yīng)謹(jǐn)慎使用以保持可讀性。

如何使用CSV模塊在Python中使用CSV文件? 如何使用CSV模塊在Python中使用CSV文件? Jun 25, 2025 am 01:03 AM

Python的csv模塊提供了讀寫(xiě)CSV文件的簡(jiǎn)單方法。 1.讀取CSV文件時(shí),可使用csv.reader()逐行讀取,並將每行數(shù)據(jù)作為字符串列表返回;若需通過(guò)列名訪問(wèn)數(shù)據(jù),則可用csv.DictReader(),它將每行映射為字典。 2.寫(xiě)入CSV文件時(shí),使用csv.writer()並調(diào)用writerow()或writerows()方法寫(xiě)入單行或多行數(shù)據(jù);若要寫(xiě)入字典數(shù)據(jù),則使用csv.DictWriter(),需先定義列名並通過(guò)writeheader()寫(xiě)入表頭。 3.處理邊緣情況時(shí),模塊自動(dòng)處理

See all articles