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

首頁 后端開發(fā) Python教程 LangGraph 狀態(tài)機(jī):管理生產(chǎn)中的復(fù)雜代理任務(wù)流

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

Nov 24, 2024 am 03:37 AM

LangGraph State Machines: Managing Complex Agent Task Flows in Production

什么是 LangGraph?

LangGraph是專門為LLM應(yīng)用程序設(shè)計(jì)的工作流編排框架。其核心原則是:

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

想想購物:瀏覽→添加到購物車→結(jié)賬→付款。 LangGraph 幫助我們有效地管理此類工作流程。

核心概念

1. 國家

狀態(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í)示例:智能客戶服務(wù)系統(tǒng)

讓我們看一個(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)簡單明了
    • 僅存儲(chǔ)必要的信息
    • 考慮序列化要求
  2. 轉(zhuǎn)換邏輯優(yōu)化

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

    • 實(shí)施優(yōu)雅降級(jí)
    • 記錄詳細(xì)信息
    • 提供回滾機(jī)制
  4. 性能優(yōu)化

    • 使用異步操作
    • 實(shí)現(xiàn)狀態(tài)緩存
    • 控制狀態(tài)大小

常見陷阱和解決方案

  1. 狀態(tài)爆炸

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

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

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

概括

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

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

以上是LangGraph 狀態(tài)機(jī):管理生產(chǎn)中的復(fù)雜代理任務(wù)流的詳細(xì)內(nèi)容。更多信息請(qǐng)關(guān)注PHP中文網(wǎng)其他相關(guān)文章!

本站聲明
本文內(nèi)容由網(wǎng)友自發(fā)貢獻(xiàn),版權(quán)歸原作者所有,本站不承擔(dān)相應(yīng)法律責(zé)任。如您發(fā)現(xiàn)有涉嫌抄襲侵權(quán)的內(nèi)容,請(qǐng)聯(lián)系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脫衣機(jī)

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集成開發(fā)環(huán)境

Dreamweaver CS6

Dreamweaver CS6

視覺化網(wǎng)頁開發(fā)工具

SublimeText3 Mac版

SublimeText3 Mac版

神級(jí)代碼編輯軟件(SublimeText3)

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

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

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

"Hello,World!"程序是用Python編寫的最基礎(chǔ)示例,用于展示基本語法并驗(yàn)證開發(fā)環(huán)境是否正確配置。1.它通過一行代碼print("Hello,World!")實(shí)現(xiàn),運(yùn)行后會(huì)在控制臺(tái)輸出指定文本;2.運(yùn)行步驟包括安裝Python、使用文本編輯器編寫代碼、保存為.py文件、在終端執(zhí)行該文件;3.常見錯(cuò)誤有遺漏括號(hào)或引號(hào)、誤用大寫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的列表切片? 什么是python的列表切片? Jun 29, 2025 am 02:15 AM

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

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

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

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

參數(shù)(parameters)是定義函數(shù)時(shí)的占位符,而傳參(arguments)是調(diào)用時(shí)傳入的具體值。1.位置參數(shù)需按順序傳遞,順序錯(cuò)誤會(huì)導(dǎo)致結(jié)果錯(cuò)誤;2.關(guān)鍵字參數(shù)通過參數(shù)名指定,可改變順序且提高可讀性;3.默認(rèn)參數(shù)值在定義時(shí)賦值,避免重復(fù)代碼,但應(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模塊提供了讀寫CSV文件的簡單方法。1.讀取CSV文件時(shí),可使用csv.reader()逐行讀取,并將每行數(shù)據(jù)作為字符串列表返回;若需通過列名訪問數(shù)據(jù),則可用csv.DictReader(),它將每行映射為字典。2.寫入CSV文件時(shí),使用csv.writer()并調(diào)用writerow()或writerows()方法寫入單行或多行數(shù)據(jù);若要寫入字典數(shù)據(jù),則使用csv.DictWriter(),需先定義列名并通過writeheader()寫入表頭。3.處理邊緣情況時(shí),模塊自動(dòng)處理

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

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

See all articles