Langchain Multi Agent
Title: LangChain Multi-Agent | Beginner Tutorial\\n\\nWhen a task is too complex for a single Agent to handle, you can create multiple specialized Agents and have them collaborate like a team.\\n\\n* * *\\n\\n## Why Multi-Agent\\n\\nProblems with Single Agent:\\n\\n* Too long system_prompt causes model attention toDistributed\\n* Too many tools increases the probability of model making errors in tool selection\\n* Different types of tasks require different expertise and behavior styles\\n\\nMulti-Agent solution: Each Agent focuses on one domain, completing complex tasks through collaboration.\\n\\n* * *\\n\\n## Method 1: Sub-Agent as Tool\\n\\nCompile the Agent into a CompiledStateGraph, then register it as a tool to the parent Agent:\\n\\n## Example\\n\\nfrom dotenv import load_dotenv\\n\\n load_dotenv()\\n\\nfrom langchain.tools import tool\\n\\nfrom langchain.agents import create_agent\\n\\nfrom langchain.chat_models import init_chat_model\\n\\nfrom langchain.messages import HumanMessage\\n\\nmodel = init_chat_model("deepseek:deepseek-v4-flash", temperature=0)\\n\\n# Sub-Agent 1: Weather Expert\\n\\n@tool\\n\\ndef get_weather(city: str) ->str:\\n\\n"""Query weather"""\\n\\n data ={"Hangzhou": "SunnyοΌ25Β°C","Beijing": "Cloudy, 18Β°C"}\\n\\nreturn data.get(city, f"{city}: Data temporarily unavailable")\\n\\nweather_agent = create_agent(\\n\\n model=model,\\n\\n tools=,\\n\\n name="weather_expert",# Name used for identification and logging\\n\\n system_prompt="You are a weather expert, specializing in answering weather-related questions. Keep answers concise.",\\n\\n)\\n\\n# Sub-Agent 2: Math Expert\\n\\n@tool\\n\\ndef calculate(expression: str) ->str:\\n\\n"""Calculate mathematical expression"""\\n\\n result =eval(expression,{"__builtins__": {}},{})\\n\\nreturn f"{expression} = {result}"\\n\\nmath_agent = create_agent(\\n\\n model=model,\\n\\n tools=,\\n\\n name="math_expert",\\n\\n system_prompt="You are a math expert, specializing in mathematical calculations. Keep answers concise.",\\n\\n)\\n\\n# Parent Agent: Coordinator\\n\\n# Register sub-agents as tools\\n\\n@tool\\n\\ndef ask_weather_expert(question: str) ->str:\\n\\n"""Consult the weather expert about weather-related questions.\\nArgs:\\n\\n question: Questions about weather\\n\\n """\\n\\n result = weather_agent.invoke(\\n\\n{"messages": [HumanMessage(content=question)]}\\n\\n)\\n\\nreturn result.content\\n\\n@tool\\n\\ndef ask_math_expert(question: str) ->str:\\n\\n"""Consult the math expert about mathematical calculation problems.\\nArgs:\\n\\n question: Math calculation problem\\n\\n """\\n\\n result = math_agent.invoke(\\n\\n{"messages": [HumanMessage(content=question)]}\\n\\n)\\n\\nreturn result.content\\n\\ncoordinator = create_agent(\\n\\n model=model,\\n\\n tools=[ask_weather_expert, ask_math_expert],\\n\\n system_prompt="""You are a coordination assistant. Choose the appropriate expert based on user questions:\\n\\n - Weather-related questions β use ask_weather_expert\\n\\n - Math calculation questions β use ask_math_expert\\n\\n - If multiple domains are involved, consult each expert in sequence""",\\n\\n)\\n\\n# Test compound question\\n\\n result = coordinator.invoke({\\n\\n"messages": [HumanMessage(\\n\\n content="HangzhouHow's the weather today? If the temperature is 25 degrees, what is that in Fahrenheit?"\\n\\n"οΌFormula: Fahrenheit = Celsius Γ 9/5 + 32οΌ"\\n\\n)]\\n\\n})\\n\\nprint(result.content)\\n\\nRunning result:\\n\\nBased on the weather expert's query, Hangzhou is sunny today with a temperature of 25Β°C. Converting to Fahrenheit: 25 Γ 9/5 + 32 = 77Β°F. So Hangzhou today is 25Β°C, which is equivalent to 77Β°F, with sunny weather.\\n\\n* * *\\n\\n## Method 2: Using name Parameter to Distinguish Agents\\n\\nWhen embedding sub-agents as tools, setting the name parameter helps trace message sources:\\n\\n## Example\\n\\n# Role of name parameter:\\n# 1. Used in the compiled graph\\n# 2. Used when embedding as sub-graph nodes in parent graph\\n# 3. All AI messages are tagged with this name\\n\\nagent = create_agent(\\n\\n model=model,\\n\\n tools=[...],\\n\\n name="customer_service",# Name the Agent\\n\\n)\\n\\n* * *\\n\\n## Method 3: Middleware for Agent Routing\\n\\nMore complex multi-Agent scenarios can use Middleware for dynamic routing:\\n\\n## Example\\n\\nfrom langchain.agents.middleware import before_model\\n\\n# Define tool sets for different experts\\n\\n general_tools =[tool_a, tool_b]\\n\\n admin_tools =[tool_c, tool_d]\\n\\n@before_model\\n\\ndef route_by_user_role(state, runtime):\\n\\n"""Dynamically switch available tools based on user role"""\\n\\n context = runtime.context\\n\\nif context is None:\\n\\nreturn None\\n\\nuser_role = context.get("user_role","user")\\n\\n# Different roles see different tools\\n\\nif user_role =="admin":\\n\\n available_tools = general_tools + admin_tools\\n\\nelse:\\n\\n available_tools = general_tools\\n\\n# Note: before_model cannot directly modify tools,\\n# need to use wrap_model_call or request.override to implement\\n\\nreturn None\\n\\n* * *\\n\\n## Multi-Agent Architecture Patterns\\n\\n| Pattern | Structure | Applicable Scenarios |\\n| --- | --- | --- |\\n| Coordinator Pattern | One parent Agent β Multiple sub-Agent tools | Tasks with clear, classifiable types |\\n| Relay Pattern | Agent A's output β Agent B's input | Pipeline processing (generateβreviewβpolish) |\\n| Debate Pattern | Multiple Agents output in parallel β Summary decision | Problems requiring multi-perspective analysis |\\n\\n> Multi-Agent systems increase complexity and Token consumption. Don't add "multi-Agent" for the sake of itβfirst solve problems with a single Agent + well-designed system_prompt and Middleware. Only introduce multi-Agent when domain isolation or independent context is truly needed.
YouTip