langgraph 核心要点

LangGraph 采用单一状态对象的设计,所有节点都读写同一个状态对象。

整个图维护统一的 State,通过类型定义来包含多个"子状态"或字段。

多模块示例:

from langgraph.graph import StateGraph, END
from typing import TypedDict, List, Optional
import json

class MultiModuleState(TypedDict):
    # 输入模块状态
    input_text: str
    input_metadata: dict
    
    # 处理模块状态  
    analysis_result: dict
    extracted_entities: List[str]
    
    # 输出模块状态
    formatted_output: str
    response_type: str
    
    # 系统状态
    execution_log: List[str]
    current_module: str

def input_module(state: MultiModuleState) -> MultiModuleState:
    """输入处理模块"""
    state['current_module'] = 'input_processing'
    state['execution_log'].append("开始输入处理")
    
    # 处理输入
    state['input_metadata'] = {
        'length': len(state['input_text']),
        'words': len(state['input_text'].split()),
        'timestamp': '2024-01-15 10:00:00'
    }
    
    print(f"📥 输入模块完成: 处理了 {len(state['input_text'])} 个字符")
    return state

def analysis_module(state: MultiModuleState) -> MultiModuleState:
    """分析模块"""
    state['current_module'] = 'analysis'
    state['execution_log'].append("开始数据分析")
    
    # 模拟分析
    text = state['input_text']
    state['analysis_result'] = {
        'sentiment': 'positive' if '' in text else 'neutral',
        'complexity': 'high' if len(text) > 50 else 'low',
        'topics': ['问候'] if '你好' in text else ['其他']
    }
    
    state['extracted_entities'] = ['实体1', '实体2']  # 模拟实体提取
    
    print(f"🔍 分析模块完成: 情感 {state['analysis_result']['sentiment']}")
    return state

def output_module(state: MultiModuleState) -> MultiModuleState:
    """输出模块"""
    state['current_module'] = 'output'
    state['execution_log'].append("生成最终输出")
    
    # 基于分析结果生成输出
    analysis = state['analysis_result']
    if analysis['sentiment'] == 'positive':
        state['formatted_output'] = f"检测到积极情绪: {state['input_text']}"
        state['response_type'] = 'positive_response'
    else:
        state['formatted_output'] = f"标准回复: {state['input_text']}"
        state['response_type'] = 'standard_response'
    
    print(f"📤 输出模块完成: {state['response_type']}")
    return state

# 构建工作流
graph_builder = StateGraph(MultiModuleState)
graph_builder.add_node("input_processor", input_module)
graph_builder.add_node("data_analyzer", analysis_module)
graph_builder.add_node("output_generator", output_module)

graph_builder.set_entry_point("input_processor")
graph_builder.add_edge("input_processor", "data_analyzer")
graph_builder.add_edge("data_analyzer", "output_generator")
graph_builder.add_edge("output_generator", END)

graph = graph_builder.compile()

# 测试执行
print("=== 多模块状态管理测试 ===")
initial_state = {
    'input_text': '你好,今天天气很好,心情也不错!',
    'input_metadata': {},
    'analysis_result': {},
    'extracted_entities': [],
    'formatted_output': '',
    'response_type': '',
    'execution_log': [],
    'current_module': ''
}

result = graph.invoke(initial_state)
print(f"\n🎯 最终状态:")
print(json.dumps(result, ensure_ascii=False, indent=2))

 

嵌套结构:

from typing import TypedDict, List, Dict, Any

class UserInfo(TypedDict):
    name: str
    preferences: Dict[str, Any]
    history: List[str]

class ProcessingData(TypedDict):
    raw_input: str
    cleaned_input: str
    features: List[float]

class SystemMetrics(TypedDict):
    processing_time: float
    memory_usage: int
    api_calls: int

class ComplexState(TypedDict):
    # 嵌套的状态对象
    user: UserInfo
    data: ProcessingData
    metrics: SystemMetrics
    current_stage: str

def process_user_data(state: ComplexState) -> ComplexState:
    """处理用户数据"""
    state['user']['history'].append(state['data']['raw_input'])
    state['metrics']['api_calls'] += 1
    return state

def update_metrics(state: ComplexState) -> ComplexState:
    """更新系统指标"""
    state['metrics']['processing_time'] = 0.5  # 模拟处理时间
    return state

 

posted @ 2025-11-24 17:05  wangssd  阅读(0)  评论(0)    收藏  举报