{"id":204953,"date":"2025-05-29T09:03:36","date_gmt":"2025-05-29T01:03:36","guid":{"rendered":"https:\/\/server.hk\/cnblog\/204953\/"},"modified":"2025-05-29T09:03:36","modified_gmt":"2025-05-29T01:03:36","slug":"langgraph-%e7%8a%b6%e6%80%81%e6%9c%ba%ef%bc%9a%e7%ae%a1%e7%90%86%e7%94%9f%e4%ba%a7%e4%b8%ad%e7%9a%84%e5%a4%8d%e6%9d%82%e4%bb%a3%e7%90%86%e4%bb%bb%e5%8a%a1%e6%b5%81","status":"publish","type":"post","link":"https:\/\/server.hk\/cnblog\/204953\/","title":{"rendered":"LangGraph \u72b6\u6001\u673a\uff1a\u7ba1\u7406\u751f\u4ea7\u4e2d\u7684\u590d\u6742\u4ee3\u7406\u4efb\u52a1\u6d41"},"content":{"rendered":"<p><b><\/b>     <\/p>\n<h1>LangGraph \u72b6\u6001\u673a\uff1a\u7ba1\u7406\u751f\u4ea7\u4e2d\u7684\u590d\u6742\u4ee3\u7406\u4efb\u52a1\u6d41<\/h1>\n<p>\u672c\u7bc7\u6587\u7ae0\u7ed9\u5927\u5bb6\u5206\u4eab\u300aLangGraph \u72b6\u6001\u673a\uff1a\u7ba1\u7406\u751f\u4ea7\u4e2d\u7684\u590d\u6742\u4ee3\u7406\u4efb\u52a1\u6d41\u300b\uff0c\u8986\u76d6\u4e86\u6587\u7ae0\u7684\u5e38\u89c1\u57fa\u7840\u77e5\u8bc6\uff0c\u5176\u5b9e\u4e00\u4e2a\u8bed\u8a00\u7684\u5168\u90e8\u77e5\u8bc6\u70b9\u4e00\u7bc7\u6587\u7ae0\u662f\u4e0d\u53ef\u80fd\u8bf4\u5b8c\u7684\uff0c\u4f46\u5e0c\u671b\u901a\u8fc7\u8fd9\u4e9b\u95ee\u9898\uff0c\u8ba9\u8bfb\u8005\u5bf9\u81ea\u5df1\u7684\u638c\u63e1\u7a0b\u5ea6\u6709\u4e00\u5b9a\u7684\u8ba4\u8bc6(B \u6570)\uff0c\u4ece\u800c\u5f25\u8865\u81ea\u5df1\u7684\u4e0d\u8db3\uff0c\u66f4\u597d\u7684\u638c\u63e1\u5b83\u3002<\/p>\n<p><img decoding=\"async\" src=\"https:\/\/www.17golang.com\/uploads\/20241120\/1732066314673d3c0aadc97.jpg\" class=\"aligncenter\"><\/p>\n<p>langgraph\u662f\u4e13\u4e3allm\u5e94\u7528\u7a0b\u5e8f\u8bbe\u8ba1\u7684\u5de5\u4f5c\u6d41\u7f16\u6392\u6846\u67b6\u3002\u5176\u6838\u5fc3\u539f\u5219\u662f\uff1a<\/p>\n<ul>\n<li>\u5c06\u590d\u6742\u4efb\u52a1\u5206\u89e3\u4e3a\u72b6\u6001\u548c\u8f6c\u6362<\/li>\n<li>\u7ba1\u7406\u72b6\u6001\u8f6c\u6362\u903b\u8f91<\/li>\n<li>\u4efb\u52a1\u6267\u884c\u8fc7\u7a0b\u4e2d\u5404\u79cd\u5f02\u5e38\u7684\u5904\u7406<\/li>\n<\/ul>\n<p>\u60f3\u60f3\u8d2d\u7269\uff1a\u6d4f\u89c8\u2192\u6dfb\u52a0\u5230\u8d2d\u7269\u8f66\u2192\u7ed3\u8d26\u2192\u4ed8\u6b3e\u3002 langgraph \u5e2e\u52a9\u6211\u4eec\u6709\u6548\u5730\u7ba1\u7406\u6b64\u7c7b\u5de5\u4f5c\u6d41\u7a0b\u3002<\/p>\n<p>\u72b6\u6001\u5c31\u50cf\u4efb\u52a1\u6267\u884c\u4e2d\u7684\u68c0\u67e5\u70b9\uff1a<\/p>\n<pre>from typing import typeddict, list\n\nclass shoppingstate(typeddict):\n    # current state\n    current_step: str\n    # cart items\n    cart_items: list[str]\n    # total amount\n    total_amount: float\n    # user input\n    user_input: str\n\nclass shoppinggraph(stategraph):\n    def __init__(self):\n        super().__init__()\n\n        # define states\n        self.add_node(\"browse\", self.browse_products)\n        self.add_node(\"add_to_cart\", self.add_to_cart)\n        self.add_node(\"checkout\", self.checkout)\n        self.add_node(\"payment\", self.payment)\n<\/pre>\n<p>\u72b6\u6001\u8f6c\u6362\u5b9a\u4e49\u4efb\u52a1\u6d41\u7684\u201c\u8def\u7ebf\u56fe\u201d\uff1a<\/p>\n<pre>class shoppingcontroller:\n    def define_transitions(self):\n        # add transition rules\n        self.graph.add_edge(\"browse\", \"add_to_cart\")\n        self.graph.add_edge(\"add_to_cart\", \"browse\")\n        self.graph.add_edge(\"add_to_cart\", \"checkout\")\n        self.graph.add_edge(\"checkout\", \"payment\")\n\n    def should_move_to_cart(self, state: shoppingstate) -&gt; bool:\n        \"\"\"determine if we should transition to cart state\"\"\"\n        return \"add to cart\" in state[\"user_input\"].lower()\n<\/pre>\n<p>\u4e3a\u4e86\u4fdd\u8bc1\u7cfb\u7edf\u7684\u53ef\u9760\u6027\uff0c\u6211\u4eec\u9700\u8981\u6301\u4e45\u5316\u72b6\u6001\u4fe1\u606f\uff1a<\/p>\n<pre>class statemanager:\n    def __init__(self):\n        self.redis_client = redis.redis()\n\n    def save_state(self, session_id: str, state: dict):\n        \"\"\"save state to redis\"\"\"\n        self.redis_client.set(\n            f\"shopping_state:{session_id}\",\n            json.dumps(state),\n            ex=3600  # 1 hour expiration\n        )\n\n    def load_state(self, session_id: str) -&gt; dict:\n        \"\"\"load state from redis\"\"\"\n        state_data = self.redis_client.get(f\"shopping_state:{session_id}\")\n        return json.loads(state_data) if state_data else none\n<\/pre>\n<p>\u4efb\u4f55\u6b65\u9aa4\u90fd\u53ef\u80fd\u5931\u8d25\uff0c\u6211\u4eec\u9700\u8981\u4f18\u96c5\u5730\u5904\u7406\u8fd9\u4e9b\u60c5\u51b5\uff1a<\/p>\n<pre>class errorhandler:\n    def __init__(self):\n        self.max_retries = 3\n\n    async def with_retry(self, func, state: dict):\n        \"\"\"function execution with retry mechanism\"\"\"\n        retries = 0\n        while retries &lt; self.max_retries:\n            try:\n                return await func(state)\n            except exception as e:\n                retries += 1\n                if retries == self.max_retries:\n                    return self.handle_final_error(e, state)\n                await self.handle_retry(e, state, retries)\n\n    def handle_final_error(self, error, state: dict):\n        \"\"\"handle final error\"\"\"\n        # save error state\n        state[\"error\"] = str(error)\n        # rollback to last stable state\n        return self.rollback_to_last_stable_state(state)\n<\/pre>\n<p>\u8ba9\u6211\u4eec\u770b\u4e00\u4e2a\u5b9e\u9645\u7684\u4f8b\u5b50\u2014\u2014\u667a\u80fd\u5ba2\u670d\u7cfb\u7edf\uff1a<\/p>\n<pre>from langgraph.graph import stategraph, state\n\nclass customerservicestate(typeddict):\n    conversation_history: list[str]\n    current_intent: str\n    user_info: dict\n    resolved: bool\n\nclass customerservicegraph(stategraph):\n    def __init__(self):\n        super().__init__()\n\n        # initialize states\n        self.add_node(\"greeting\", self.greet_customer)\n        self.add_node(\"understand_intent\", self.analyze_intent)\n        self.add_node(\"handle_query\", self.process_query)\n        self.add_node(\"confirm_resolution\", self.check_resolution)\n\n    async def greet_customer(self, state: state):\n        \"\"\"greet customer\"\"\"\n        response = await self.llm.generate(\n            prompt=f\"\"\"\n            conversation history: {state['conversation_history']}\n            task: generate appropriate greeting\n            requirements:\n            1. maintain professional friendliness\n            2. acknowledge returning customers\n            3. ask how to help\n            \"\"\"\n        )\n        state['conversation_history'].append(f\"assistant: {response}\")\n        return state\n\n    async def analyze_intent(self, state: state):\n        \"\"\"understand user intent\"\"\"\n        response = await self.llm.generate(\n            prompt=f\"\"\"\n            conversation history: {state['conversation_history']}\n            task: analyze user intent\n            output format:\n            {{\n                \"intent\": \"refund\/inquiry\/complaint\/other\",\n                \"confidence\": 0.95,\n                \"details\": \"specific description\"\n            }}\n            \"\"\"\n        )\n        state['current_intent'] = json.loads(response)\n        return state\n<\/pre>\n<pre># Initialize system\ngraph = CustomerServiceGraph()\nstate_manager = StateManager()\nerror_handler = ErrorHandler()\n\nasync def handle_customer_query(user_id: str, message: str):\n    # Load or create state\n    state = state_manager.load_state(user_id) or {\n        \"conversation_history\": [],\n        \"current_intent\": None,\n        \"user_info\": {},\n        \"resolved\": False\n    }\n\n    # Add user message\n    state[\"conversation_history\"].append(f\"User: {message}\")\n\n    # Execute state machine flow\n    try:\n        result = await graph.run(state)\n        # Save state\n        state_manager.save_state(user_id, result)\n        return result[\"conversation_history\"][-1]\n    except Exception as e:\n        return await error_handler.with_retry(\n            graph.run,\n            state\n        )\n<\/pre>\n<ol>\n<li>\n<p><strong>\u9648\u8ff0\u8bbe\u8ba1\u539f\u5219<\/strong><\/p>\n<ul>\n<li>\u4fdd\u6301\u72b6\u6001\u7b80\u5355\u660e\u4e86<\/li>\n<li>\u4ec5\u5b58\u50a8\u5fc5\u8981\u7684\u4fe1\u606f<\/li>\n<li>\u8003\u8651\u5e8f\u5217\u5316\u8981\u6c42<\/li>\n<\/ul>\n<\/li>\n<li>\n<p><strong>\u8f6c\u6362\u903b\u8f91\u4f18\u5316<\/strong><\/p>\n<ul>\n<li>\u4f7f\u7528\u6761\u4ef6\u8f6c\u6362<\/li>\n<li>\u907f\u514d\u65e0\u9650\u5faa\u73af<\/li>\n<li>\u8bbe\u7f6e\u6700\u5927\u6b65\u6570\u9650\u5236<\/li>\n<\/ul>\n<\/li>\n<li>\n<p><strong>\u9519\u8bef\u5904\u7406\u7b56\u7565<\/strong><\/p>\n<ul>\n<li>\u5b9e\u65bd\u4f18\u96c5\u964d\u7ea7<\/li>\n<li>\u8bb0\u5f55\u8be6\u7ec6\u4fe1\u606f<\/li>\n<li>\u63d0\u4f9b\u56de\u6eda\u673a\u5236<\/li>\n<\/ul>\n<\/li>\n<li>\n<p><strong>\u6027\u80fd\u4f18\u5316<\/strong><\/p>\n<ul>\n<li>\u4f7f\u7528\u5f02\u6b65\u64cd\u4f5c<\/li>\n<li>\u5b9e\u73b0\u72b6\u6001\u7f13\u5b58<\/li>\n<li>\u63a7\u5236\u72b6\u6001\u5927\u5c0f<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<ol>\n<li>\n<p><strong>\u72b6\u6001\u7206\u70b8<\/strong><\/p>\n<ul>\n<li>\u95ee\u9898\uff1a\u72b6\u6001\u592a\u591a\u5bfc\u81f4\u7ef4\u62a4\u56f0\u96be<\/li>\n<li>\u89e3\u51b3\u65b9\u6848\uff1a\u5408\u5e76\u76f8\u4f3c\u7684\u72b6\u6001\uff0c\u4f7f\u7528\u72b6\u6001\u7ec4\u5408\u800c\u4e0d\u662f\u521b\u5efa\u65b0\u7684<\/li>\n<\/ul>\n<\/li>\n<li>\n<p><strong>\u6b7b\u9501\u60c5\u51b5<\/strong><\/p>\n<ul>\n<li>\u95ee\u9898\uff1a\u5faa\u73af\u72b6\u6001\u8f6c\u6362\u5bfc\u81f4\u4efb\u52a1\u6302\u8d77<\/li>\n<li>\u89e3\u51b3\u65b9\u6848\uff1a\u6dfb\u52a0\u8d85\u65f6\u673a\u5236\u548c\u5f3a\u5236\u9000\u51fa\u6761\u4ef6<\/li>\n<\/ul>\n<\/li>\n<li>\n<p><strong>\u72b6\u6001\u4e00\u81f4\u6027<\/strong><\/p>\n<ul>\n<li>\u95ee\u9898\uff1a\u5206\u5e03\u5f0f\u73af\u5883\u4e2d\u72b6\u6001\u4e0d\u4e00\u81f4<\/li>\n<li>\u89e3\u51b3\u65b9\u6848\uff1a\u4f7f\u7528\u5206\u5e03\u5f0f\u9501\u548c\u4e8b\u52a1\u673a\u5236<\/li>\n<\/ul>\n<\/li>\n<\/ol>\n<p>langgraph \u72b6\u6001\u673a\u4e3a\u7ba1\u7406\u590d\u6742\u7684 ai agent \u4efb\u52a1\u6d41\u63d0\u4f9b\u4e86\u5f3a\u5927\u7684\u89e3\u51b3\u65b9\u6848\uff1a<\/p>\n<ul>\n<li>\u6e05\u6670\u7684\u4efb\u52a1\u6d41\u7a0b\u7ba1\u7406<\/li>\n<li>\u53ef\u9760\u7684\u72b6\u6001\u6301\u4e45\u6027<\/li>\n<li>\u5168\u9762\u7684\u9519\u8bef\u5904\u7406<\/li>\n<li>\u7075\u6d3b\u7684\u6269\u5c55\u6027<\/li>\n<\/ul>\n<p>\u4eca\u5929\u5e26\u5927\u5bb6\u4e86\u89e3\u4e86\u7684\u76f8\u5173\u77e5\u8bc6\uff0c\u5e0c\u671b\u5bf9\u4f60\u6709\u6240\u5e2e\u52a9\uff1b\u5173\u4e8e\u6587\u7ae0\u7684\u6280\u672f\u77e5\u8bc6\u6211\u4eec\u4f1a\u4e00\u70b9\u70b9\u6df1\u5165\u4ecb\u7ecd\uff0c\u6b22\u8fce\u5927\u5bb6\u5173\u6ce8\u516c\u4f17\u53f7\uff0c\u4e00\u8d77\u5b66\u4e60\u7f16\u7a0b~<\/p>\n<p>      \u7248\u672c\u58f0\u660e \u672c\u6587\u8f6c\u8f7d\u4e8e\uff1adev.to \u5982\u6709\u4fb5\u72af\uff0c\u8bf7\u8054\u7cfb\u5220\u9664<\/p>\n","protected":false},"excerpt":{"rendered":"<p>LangGraph \u72b6\u6001\u673a\uff1a\u7ba1\u7406&#46;&#46;&#46;<\/p>\n","protected":false},"author":1,"featured_media":0,"comment_status":"closed","ping_status":"","sticky":false,"template":"","format":"standard","meta":{"footnotes":""},"categories":[4925],"tags":[],"class_list":["post-204953","post","type-post","status-publish","format-standard","hentry","category-4925"],"_links":{"self":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/204953","targetHints":{"allow":["GET"]}}],"collection":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts"}],"about":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/types\/post"}],"author":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/users\/1"}],"replies":[{"embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/comments?post=204953"}],"version-history":[{"count":0,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/posts\/204953\/revisions"}],"wp:attachment":[{"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/media?parent=204953"}],"wp:term":[{"taxonomy":"category","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/categories?post=204953"},{"taxonomy":"post_tag","embeddable":true,"href":"https:\/\/server.hk\/cnblog\/wp-json\/wp\/v2\/tags?post=204953"}],"curies":[{"name":"wp","href":"https:\/\/api.w.org\/{rel}","templated":true}]}}