
    /Ui                         d dl mZmZmZ d dlmZ d dlmZmZm	Z	m
Z
mZmZmZmZ d dlmZ  G d de      Z ede      Ze
e   Zd	ed
ee   defdZdedee   dedefdZedddee   ded	ede
e   dz  def
dZy)    )STARTMessagesState
StateGraph)Pregel)AnyLiteralOptionalTypeTypeVarUnionget_args
get_origin)get_handoff_destinationsc                   "    e Zd ZU dZee   ed<   y)
SwarmStatez'State schema for the multi-agent swarm.active_agentN)__name__
__module____qualname____doc__r	   str__annotations__     q/home/jay/workspace/tools/ai-image-gen/jaaz-app/server/venv/lib/python3.12/site-packages/langgraph_swarm/swarm.pyr   r      s    1
 3-r   r   StateSchema)boundstate_schemaagent_namesreturnc                 j   | j                   d   }|t        u }t        |      t        u xr t	        |      d   t        u }|s|s| S t        | j                   | fdi | j                   i      }t        j                  t        |            }|rt        |   |j                   d<   |S ||j                   d<   |S )zKUpdate the state schema to use Literal with agent names for 'active_agent'.r   r   r   )r   r   r   r   r   typer   r   __getitem__tupler	   )r   r   active_agent_annotationis_str_typeis_optional_strupdated_schemaliteral_types          r    _update_state_schema_agent_namesr*      s    
 +::>J *S0K*+u4dBY9Z[\9]ad9d 
 ?  
!		<|;;<=N &&u['9:L 9A,9O&&~6  :F&&~6r   builderroute_todefault_active_agentc                    | j                   | j                     }d|vrt        d      |vrt        d d|       dt        ffd}| j	                  t
        ||       | S )a_  Add a router to the currently active agent to the StateGraph.

    Args:
        builder: The graph builder (StateGraph) to add the router to.
        route_to: A list of agent (node) names to route to.
        default_active_agent: Name of the agent to route to by default (if no agents are currently active).

    Returns:
        StateGraph with the router added.

    Example:
        ```python
        from langgraph.checkpoint.memory import InMemorySaver
        from langgraph.prebuilt import create_react_agent
        from langgraph.graph import StateGraph
        from langgraph_swarm import SwarmState, create_handoff_tool, add_active_agent_router

        def add(a: int, b: int) -> int:
            '''Add two numbers'''
            return a + b

        alice = create_react_agent(
            "openai:gpt-4o",
            [add, create_handoff_tool(agent_name="Bob")],
            prompt="You are Alice, an addition expert.",
            name="Alice",
        )

        bob = create_react_agent(
            "openai:gpt-4o",
            [create_handoff_tool(agent_name="Alice", description="Transfer to Alice, she can help with math")],
            prompt="You are Bob, you speak like a pirate.",
            name="Bob",
        )

        checkpointer = InMemorySaver()
        workflow = (
            StateGraph(SwarmState)
            .add_node(alice, destinations=("Bob",))
            .add_node(bob, destinations=("Alice",))
        )
        # this is the router that enables us to keep track of the last active agent
        workflow = add_active_agent_router(
            builder=workflow,
            route_to=["Alice", "Bob"],
            default_active_agent="Alice",
        )

        # compile the workflow
        app = workflow.compile(checkpointer=checkpointer)

        config = {"configurable": {"thread_id": "1"}}
        turn_1 = app.invoke(
            {"messages": [{"role": "user", "content": "i'd like to speak to Bob"}]},
            config,
        )
        turn_2 = app.invoke(
            {"messages": [{"role": "user", "content": "what's 5 + 7?"}]},
            config,
        )
        ```
    r   z@Missing required key 'active_agent' in in builder's state_schemazDefault active agent 'z' not found in routes statec                 (    | j                  d      S )Nr   )get)r/   r-   s    r   route_to_active_agentz6add_active_agent_router.<locals>.route_to_active_agent   s    yy)=>>r   )path_map)schemasschema
ValueErrordictadd_conditional_edgesr   )r+   r,   r-   channelsr2   s     `  r   add_active_agent_routerr:   8   s    H w~~.HX%[\\8+$%9$::PQYPZ[
 	
?T ? !!%)>!RNr   N)r   config_schemaagentsr;   c          
      L   |j                   j                  d      }|t        d      | D cg c]  }|j                   }}t	        ||      }t        ||      }t        |||       | D ]2  }|j                  |j                  |t        t        |                   4 |S c c}w )a  Create a multi-agent swarm.

    Args:
        agents: List of agents to add to the swarm
            An agent can be a LangGraph [CompiledStateGraph](https://langchain-ai.github.io/langgraph/reference/graphs/#langgraph.graph.state.CompiledStateGraph),
            a functional API [workflow](https://langchain-ai.github.io/langgraph/reference/func/#langgraph.func.entrypoint),
            or any other [Pregel](https://langchain-ai.github.io/langgraph/reference/pregel/#langgraph.pregel.Pregel) object.
        default_active_agent: Name of the agent to route to by default (if no agents are currently active).
        state_schema: State schema to use for the multi-agent graph.
        config_schema: An optional schema for configuration.
            Use this to expose configurable parameters via `swarm.config_specs`.

    Returns:
        A multi-agent swarm StateGraph.

    Example:
        ```python
        from langgraph.checkpoint.memory import InMemorySaver
        from langgraph.prebuilt import create_react_agent
        from langgraph_swarm import create_handoff_tool, create_swarm

        def add(a: int, b: int) -> int:
            '''Add two numbers'''
            return a + b

        alice = create_react_agent(
            "openai:gpt-4o",
            [add, create_handoff_tool(agent_name="Bob")],
            prompt="You are Alice, an addition expert.",
            name="Alice",
        )

        bob = create_react_agent(
            "openai:gpt-4o",
            [create_handoff_tool(agent_name="Alice", description="Transfer to Alice, she can help with math")],
            prompt="You are Bob, you speak like a pirate.",
            name="Bob",
        )

        checkpointer = InMemorySaver()
        workflow = create_swarm(
            [alice, bob],
            default_active_agent="Alice"
        )
        app = workflow.compile(checkpointer=checkpointer)

        config = {"configurable": {"thread_id": "1"}}
        turn_1 = app.invoke(
            {"messages": [{"role": "user", "content": "i'd like to speak to Bob"}]},
            config,
        )
        turn_2 = app.invoke(
            {"messages": [{"role": "user", "content": "what's 5 + 7?"}]},
            config,
        )
        ```
    r   z3Missing required key 'active_agent' in state_schema)r,   r-   )destinations)
r   r1   r6   namer*   r   r:   add_noder$   r   )r<   r-   r   r;   r%   agentr   r+   s           r   create_swarmrB      s    @ +::>>~N&NOO+12%5::2K23L+NL}5G1
  
JJ7>? 	 	

 N 3s   B!)langgraph.graphr   r   r   langgraph.pregelr   typing_extensionsr   r   r	   r
   r   r   r   r   langgraph_swarm.handoffr   r   r   StateSchemaTypelistr   r*   r:   rB   r   r   r   <module>rI      s    < < # ` ` ` <    m:6{# ! 04S	  FQQ 3iQ 	Q
 Qp %/&*SLS S "	S
 9t#S Sr   