from langchain_core.tools import tool# Research Agent Tools@tooldef search_information(query: str) -> str: """Search for information on a topic. Args: query: The search query """ # Mock implementation return f"Research findings: {query} is a complex topic with multiple facets..."@tooldef summarize_research(text: str) -> str: """Summarize research findings. Args: text: Text to summarize """ words = text.split()[:20] return f"Summary: {' '.join(words)}..."# Writer Agent Tools@tooldef draft_content(topic: str, style: str = "professional") -> str: """Draft content on a topic. Args: topic: Topic to write about style: Writing style (professional, casual, technical) """ return f"Draft ({style} style): Content about {topic}..."@tooldef edit_content(content: str) -> str: """Edit and improve content. Args: content: Content to edit """ return f"Edited: {content} [improved grammar and clarity]"# Analyst Agent Tools@tooldef analyze_data(data: str) -> str: """Analyze data and provide insights. Args: data: Data to analyze """ return f"Analysis: {data} shows interesting patterns..."@tooldef create_report(analysis: str) -> str: """Create a report from analysis. Args: analysis: Analysis to report on """ return f"Report: {analysis} [formatted as executive summary]"research_tools = [search_information, summarize_research]writer_tools = [draft_content, edit_content]analyst_tools = [analyze_data, create_report]
3
Create specialized agent nodes
Build individual agents with different capabilities.
from langchain_openai import ChatOpenAIfrom langchain_core.messages import SystemMessage, HumanMessage# Initialize models for different agentsmodel = ChatOpenAI(model="gpt-4", temperature=0.7)def create_agent_node(name: str, system_prompt: str, tools: list): """Factory function to create specialized agents.""" model_with_tools = model.bind_tools(tools) def agent_node(state: MultiAgentState) -> dict: messages = state["messages"] # Add agent-specific system prompt full_messages = [ SystemMessage(content=system_prompt), *messages ] response = model_with_tools.invoke(full_messages) # Update task results task_results = state.get("task_results", {}) task_results[name] = response.content return { "messages": [response], "current_agent": name, "task_results": task_results } return agent_node# Create specialized agentsresearcher = create_agent_node( "researcher", "You are a research specialist. Search for information and summarize findings.", research_tools)writer = create_agent_node( "writer", "You are a content writer. Create well-written, engaging content based on research.", writer_tools)analyst = create_agent_node( "analyst", "You are a data analyst. Analyze information and create insightful reports.", analyst_tools)
4
Create supervisor agent
Build a supervisor that routes work to specialized agents.
from langchain_core.pydantic_v1 import BaseModel, Fieldclass RouteDecision(BaseModel): """Decision on which agent to route to next.""" next_agent: Literal["researcher", "writer", "analyst", "finish"] = Field( description="The next agent to handle the task, or 'finish' if complete" ) reasoning: str = Field( description="Brief explanation of why this agent was chosen" )SUPERVISOR_PROMPT = """You are a supervisor managing a team of specialized agents:1. RESEARCHER: Searches for information and summarizes findings2. WRITER: Creates written content based on research3. ANALYST: Analyzes data and creates reportsYour job is to route tasks to the appropriate agent based on the current state.Review the conversation history and task results to decide the next step.Choose 'finish' when the task is complete."""supervisor_model = model.with_structured_output(RouteDecision)def supervisor_node(state: MultiAgentState) -> dict: """Supervisor that routes to specialized agents.""" messages = state["messages"] task_results = state.get("task_results", {}) # Build context for supervisor context = f"""Current state: - Completed tasks: {list(task_results.keys())} - Last agent: {state.get('current_agent', 'none')} Decide which agent should handle the next step. """ full_messages = [ SystemMessage(content=SUPERVISOR_PROMPT), HumanMessage(content=context), *messages ] decision = supervisor_model.invoke(full_messages) return { "next_agent": decision.next_agent, "messages": [HumanMessage(content=f"Routing to {decision.next_agent}: {decision.reasoning}")] }
from langchain_core.messages import HumanMessage# Complex task requiring multiple agentsresult = app.invoke({ "messages": [ HumanMessage( content="""Research the benefits of LangGraph, write a brief article about it, and provide an analysis of its key features.""" ) ], "task_results": {}, "current_agent": "", "next_agent": ""})# View results from each agentprint("\nTask Results:")for agent, result in result["task_results"].items(): print(f"\n{agent.upper()}:") print(result) print("-" * 50)print(f"\nTotal messages: {len(result['messages'])}")print(f"Final answer: {result['messages'][-1].content}")
Task Results:RESEARCHER:Research on LangGraph: comprehensive findings...--------------------------------------------------ARTICLE:Article about LangGraph: well-written content...--------------------------------------------------Total messages: 8Final answer: Task completed successfully with contributions from researcher and writer.