LangGraph Swarm

0.1.0 · active · verified Fri Apr 17

LangGraph Swarm provides a high-level API for creating and managing a swarm of AI agents, making it easier to build complex multi-agent systems using LangGraph. It is designed to abstract away common patterns in multi-agent orchestration. The current version is 0.1.0, and releases are expected to follow LangGraph's development cadence or as significant features are added.

Common errors

Warnings

Install

Imports

Quickstart

This quickstart demonstrates how to create a simple multi-agent swarm with two agents (Researcher, Writer) using `AgentNode` and orchestrate their interaction using `SwarmGraph`. It initializes an `AgentSwarm` and invokes it with a task, showing how to set up a basic workflow. Ensure your `OPENAI_API_KEY` is set in your environment for this example to run.

import os
from langchain_openai import ChatOpenAI
from langgraph_swarm import AgentSwarm, AgentNode, SwarmGraph
from langgraph_swarm.nodes import LLMNode

# Set your OpenAI API key
os.environ["OPENAI_API_KEY"] = os.environ.get("OPENAI_API_KEY", "")

if not os.environ["OPENAI_API_KEY"]:
    print("Warning: OPENAI_API_KEY environment variable not set. Skipping quickstart.")
else:
    llm = ChatOpenAI(model="gpt-4o", temperature=0)

    # Define the agents (nodes in the swarm)
    research_agent = AgentNode(
        name="Researcher",
        description="Researches given topics and provides factual information.",
        llm=llm, # Example LLM, replace with actual agent logic if needed
        tools=[]
    )
    writer_agent = AgentNode(
        name="Writer",
        description="Writes creative content based on research.",
        llm=llm,
        tools=[]
    )

    # Create a SwarmGraph
    graph = SwarmGraph()

    # Add agents to the graph
    graph.add_agent(research_agent)
    graph.add_agent(writer_agent)

    # Define the workflow (how agents interact)
    graph.add_workflow(
        entry_point=research_agent.name,
        edges={research_agent.name: writer_agent.name},
        # The writer agent should only activate if research is complete
        # Add conditional logic or specific messages to trigger in a real scenario
        exit_point=writer_agent.name
    )

    # Create the AgentSwarm instance
    swarm = AgentSwarm(graph=graph, llm=llm) # LLM for internal swarm coordination if needed

    # Invoke the swarm with an initial task
    task = "Write a short summary about the benefits of multi-agent systems."
    print(f"\n--- Invoking swarm with task: '{task}' ---\n")
    result = swarm.invoke({"messages": [("user", task)]})

    print("\n--- Swarm execution complete ---\n")
    print(f"Final result: {result}")

    # Expected output structure might vary, but should contain the agents' messages.
    # print(result["messages"][-1].content) # Example access to final message

view raw JSON →