Metadata-Version: 2.4
Name: vs-graph
Version: 0.1.0
Summary: JSON-driven graph library for building agentic applications
License:                                  Apache License
                                   Version 2.0, January 2004
                                http://www.apache.org/licenses/
        
           TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
        
           1. Definitions.
        
              "License" shall mean the terms and conditions for use, reproduction,
              and distribution as defined by Sections 1 through 9 of this document.
        
              "Licensor" shall mean the copyright owner or entity authorized by
              the copyright owner that is granting the License.
        
              "Legal Entity" shall mean the union of the acting entity and all
              other entities that control, are controlled by, or are under common
              control with that entity. For the purposes of this definition,
              "control" means (i) the power, direct or indirect, to cause the
              direction or management of such entity, whether by contract or
              otherwise, or (ii) ownership of fifty percent (50%) or more of the
              outstanding shares, or (iii) beneficial ownership of such entity.
        
              "You" (or "Your") shall mean an individual or Legal Entity
              exercising permissions granted by this License.
        
              "Source" form shall mean the preferred form for making modifications,
              including but not limited to software source code, documentation
              source, and configuration files.
        
              "Object" form shall mean any form resulting from mechanical
              transformation or translation of a Source form, including but
              not limited to compiled object code, generated documentation,
              and conversions to other media types.
        
              "Work" shall mean the work of authorship made available under
              the License, as indicated by a copyright notice that is included in
              or attached to the work (an example is provided in the Appendix below).
        
              "Derivative Works" shall mean any work, whether in Source or Object
              form, that is based on (or derived from) the Work and for which the
              editorial revisions, annotations, elaborations, or other modifications
              represent, as a whole, an original work of authorship. For the purposes
              of this License, Derivative Works shall not include works that remain
              separable from, or merely link (or bind by name) to the interfaces of,
              the Work and derivative works thereof.
        
              "Contribution" shall mean, as submitted to the Licensor for inclusion
              in the Work by the copyright owner or by an individual or Legal Entity
              authorized to submit on behalf of the copyright owner. For the purposes
              of this definition, "submitted" means any form of electronic, verbal,
              or written communication sent to the Licensor or its representatives,
              including but not limited to communication on electronic mailing lists,
              source code control systems, and issue tracking systems that are managed
              by, or on behalf of, the Licensor for the purpose of discussing and
              improving the Work, but excluding communication that is conspicuously
              marked or designated in writing by the copyright owner as "Not a
              Contribution."
        
              "Contributor" shall mean Licensor and any Legal Entity on behalf of
              whom a Contribution has been received by the Licensor and incorporated
              within the Work.
        
           2. Grant of Copyright License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              copyright license to reproduce, prepare Derivative Works of,
              publicly display, publicly perform, sublicense, and distribute the
              Work and such Derivative Works in Source or Object form.
        
           3. Grant of Patent License. Subject to the terms and conditions of
              this License, each Contributor hereby grants to You a perpetual,
              worldwide, non-exclusive, no-charge, royalty-free, irrevocable
              (except as stated in this section) patent license to make, have made,
              use, offer to sell, sell, import, and otherwise transfer the Work,
              where such license applies only to those patent claims licensable
              by such Contributor that are necessarily infringed by their
              Contribution(s) alone or by the combination of their Contribution(s)
              with the Work to which such Contribution(s) was submitted. If You
              institute patent litigation against any entity (including a cross-claim
              or counterclaim in a lawsuit) alleging that the Work or any
              Contribution embodied within the Work constitutes direct or
              contributory patent infringement, then any patent licenses granted to
              You under this License for that Work shall terminate as of the date
              such litigation is filed.
        
           4. Redistribution. You may reproduce and distribute copies of the
              Work or Derivative Works thereof in any medium, with or without
              modifications, and in Source or Object form, provided that You
              meet the following conditions:
        
              (a) You must give any other recipients of the Work or Derivative
                  Works a copy of this License; and
        
              (b) You must cause any modified files to carry prominent notices
                  stating that You changed the files; and
        
              (c) You must retain, in the Source form of any Derivative Works
                  that You distribute, all copyright, patent, trademark, and
                  attribution notices from the Source form of the Work,
                  excluding those notices that do not pertain to any part of
                  the Derivative Works; and
        
              (d) If the Work includes a "NOTICE" file as part of its distribution,
                  You must include a readable copy of the attribution notices
                  contained within such NOTICE file, in at least one of the
                  following places: within a NOTICE text file distributed as part
                  of the Derivative Works; within the Source form or documentation,
                  if provided along with the Derivative Works; or, within a display
                  generated by the Derivative Works, if and wherever such
                  third-party notices normally appear. The contents of the NOTICE
                  file are for informational purposes only and do not modify the
                  License. You may add Your own attribution notices within
                  Derivative Works that You distribute, alongside or as an addendum
                  to the NOTICE text from the Work, provided that such additional
                  attribution notices cannot be construed as modifying the License.
        
              You may add Your own license statement for Your modifications and
              may provide additional grant of rights to use, modify, and distribute
              Your modifications.
        
           5. Submission of Contributions. Unless You explicitly state otherwise,
              any Contribution intentionally submitted for inclusion in the Work
              by You to the Licensor shall be under the terms and conditions of
              this License, without any additional terms or conditions.
              Notwithstanding the above, nothing herein shall supersede or modify
              the terms of any separate license agreement you may have executed
              with Licensor regarding such Contributions.
        
           6. Trademarks. This License does not grant permission to use the trade
              names, trademarks, service marks, or product names of the Licensor,
              except as required for reasonable and customary use in describing the
              origin of the Work and reproducing the content of the NOTICE file.
        
           7. Disclaimer of Warranty. Unless required by applicable law or
              agreed to in writing, Licensor provides the Work (and each
              Contributor provides its Contributions) on an "AS IS" BASIS,
              WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
              implied, including, without limitation, any conditions of TITLE,
              NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A PARTICULAR
              PURPOSE. You are solely responsible for determining the
              appropriateness of using or reproducing the Work and assume any
              risks associated with Your exercise of permissions under this License.
        
           8. Limitation of Liability. In no event and under no legal theory,
              whether in tort (including negligence), contract, or otherwise,
              unless required by applicable law (such as deliberate and grossly
              negligent acts) or agreed to in writing, shall any Contributor be
              liable to You for damages, including any direct, indirect, special,
              incidental, or exemplary damages of any character arising as a
              result of this License or out of the use or inability to use the
              Work (including but not limited to damages for loss of goodwill,
              work stoppage, computer failure or malfunction, or all other
              commercial damages or losses), even if such Contributor has been
              advised of the possibility of such damages.
        
           9. Accepting Warranty or Additional Liability. While redistributing
              the Work or Derivative Works thereof, You may choose to offer,
              and charge a fee for, acceptance of support, warranty, indemnity,
              or other liability obligations and/or rights consistent with this
              License. However, in accepting such obligations, You may act only
              on Your own behalf and on Your sole responsibility, not on behalf
              of any other Contributor, and only if You agree to indemnify,
              defend, and hold each Contributor harmless for any liability
              incurred by, or claims asserted against, such Contributor by reason
              of your accepting any such warranty or additional liability.
        
           END OF TERMS AND CONDITIONS
        
           Copyright 2026 VivekaSutra. All rights reserved.
        
           Licensed under the Apache License, Version 2.0 (the "License");
           you may not use this file except in compliance with the License.
           You may obtain a copy of the License at
        
               http://www.apache.org/licenses/LICENSE-2.0
        
           Unless required by applicable law or agreed to in writing, software
           distributed under the License is distributed on an "AS IS" BASIS,
           WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
           implied. See the License for the specific language governing
           permissions and limitations under the License.
        
Keywords: graph,agent,langgraph,agentic,viveka,vs
Classifier: Development Status :: 3 - Alpha
Classifier: Intended Audience :: Developers
Classifier: License :: Other/Proprietary License
Classifier: Programming Language :: Python :: 3.11
Classifier: Programming Language :: Python :: 3.12
Classifier: Programming Language :: Python :: 3.13
Classifier: Topic :: Software Development :: Libraries :: Python Modules
Classifier: Framework :: AsyncIO
Classifier: Typing :: Typed
Requires-Python: >=3.11
Description-Content-Type: text/markdown
License-File: LICENSE.txt
Requires-Dist: langgraph>=0.2
Requires-Dist: vs-common
Provides-Extra: redis
Requires-Dist: redis>=5.0; extra == "redis"
Requires-Dist: hiredis>=2.0; extra == "redis"
Provides-Extra: dev
Requires-Dist: build; extra == "dev"
Requires-Dist: twine; extra == "dev"
Requires-Dist: pytest>=8.0; extra == "dev"
Requires-Dist: pytest-asyncio>=0.23; extra == "dev"
Dynamic: license-file

# vs-graph

JSON-driven LangGraph wrapper for building agentic workflows — define graph topology in JSON, implement nodes and edges in Python, and get a fully wired, observable, checkpointed execution graph.

---

## Overview

`vs-graph` wraps [LangGraph](https://github.com/langchain-ai/langgraph) and eliminates the boilerplate of building agentic graphs: wiring nodes, routing edges, setting up checkpointers, and propagating trace events. You declare the graph structure in a JSON file, implement node logic by extending `VsBaseNode`, and wire routing logic by extending `VsBaseConditionalEdge` or `VsDynamicFanOutEdge`. The library handles everything else.

The `@node` and `@edge` decorators self-register implementations at import time. The `@graph` decorator on a graph class specifies which packages to auto-import so no manual import list is required.

---

## The Problem It Solves

### Without vs-graph

```python
# Manual LangGraph wiring — every graph requires this boilerplate
from langgraph.graph import StateGraph, START, END

sg = StateGraph(MyState)
sg.add_node("classifier", classifier_node.invoke)
sg.add_node("executor", executor_node.invoke)
sg.add_node("responder", responder_node.invoke)
sg.add_edge(START, "classifier")
sg.add_conditional_edges("classifier", routing_fn, {"execute": "executor", "default": "responder"})
sg.add_edge("executor", "responder")
sg.add_edge("responder", END)
checkpointer = MemorySaver()
graph = sg.compile(checkpointer=checkpointer)
```

Every graph has this same boilerplate. Adding a node requires updating both code and wiring.

### With vs-graph

```python
# graph topology is in JSON
# Python only contains business logic

@graph(nodes=["myapp.graph.nodes"], edges=["myapp.graph.edges"])
class MyGraph(VsBaseGraph[MyState]):
    def __init__(self):
        with open("my_graph.json") as f:
            graph_json = json.load(f)
        super().__init__(graph_json=graph_json, state_class=MyState)
        self.build()

graph = MyGraph()
result = await graph.invoke({"trace_id": "", "error": None, "user_input": "hello"})
```

---

## How It All Fits Together

```
@graph(nodes=[...], edges=[...])
class MyGraph(VsBaseGraph[MyState])
    └── __init__: load JSON, call build()

build()
    ├── _auto_import_packages()     # walks node/edge packages, triggers @node/@edge registration
    ├── _instantiate_nodes()        # VsNodeRegistry.create() for each JSON node definition
    ├── _instantiate_edges()        # VsEdgeRegistry.create() for conditional/dynamic_fan_out
    ├── _validate_graph()           # checks all node ids, edge targets, and exit nodes
    ├── _load_checkpointer()        # reads config.ini [graph] section
    └── _build_langgraph()          # compiles StateGraph with checkpointer

invoke(state)
    ├── auto-generates trace_id if not set
    └── StateGraph.ainvoke(state)
            └── per node: VsBaseNode.invoke()
                    ├── trace: "node started"
                    ├── execute(state)          ← your business logic
                    └── trace: "node completed" / "node failed"
            └── per conditional / dynamic_fan_out edge: async VsBaseEdge.route()
                    ├── _evaluate(state) / get_sends(state)   ← your routing logic
                    └── trace: "routing to next_node" / "fanning out to N branch(es)"
            (direct and fan_out edges are plain LangGraph edges — no wrapper, no trace)
```

---

## Graph JSON

The JSON file declares the graph topology. Python classes are referenced by the `name` field in each node/edge definition — matching the name passed to `@node(name="...")` or `@edge(name="...")`.

```json
{
  "version": "1.0",
  "name": "my_graph",
  "entry_node": "classifier",
  "exit_nodes": ["responder"],
  "nodes": [
    { "id": "classifier", "name": "classifier_node", "config": {} },
    { "id": "executor",   "name": "executor_node",   "config": {} },
    { "id": "responder",  "name": "responder_node",  "config": {} }
  ],
  "edges": [
    {
      "type": "conditional",
      "source": "classifier",
      "edge_class": "classifier_routing_edge",
      "route": {
        "execute": "executor",
        "default": "responder"
      }
    },
    { "type": "direct", "source": "executor", "target": "responder" }
  ]
}
```

### JSON Fields

| Field | Required | Description |
|---|---|---|
| `name` | Yes | Graph name — used in logs and error messages |
| `version` | No | Version string (default `"1.0"`) |
| `entry_node` | Yes | `id` of the node that receives the initial state |
| `exit_nodes` | Yes | List of node `id`s that connect to `END` |
| `nodes` | Yes | Array of node definitions |
| `nodes[].id` | Yes | Unique node id within this graph — used in edge source/target fields |
| `nodes[].name` | Yes | Registry name — must match the `@node(name="...")` decorator value |
| `nodes[].config` | No | Arbitrary dict passed to the node constructor as `self.config` |
| `edges` | No | Array of edge definitions |
| `edges[].type` | Yes | `direct`, `fan_out`, `conditional`, or `dynamic_fan_out` |
| `edges[].source` | Yes | Node `id` this edge originates from |
| `edges[].target` | For `direct` | Target node `id` |
| `edges[].targets` | For `fan_out` | Array of target node `id`s (minimum 2) |
| `edges[].edge_class` | For `conditional`, `dynamic_fan_out` | Registry name matching `@edge(name="...")` |
| `edges[].route` | For `conditional` | Map of route keys to target node `id`s — must include `"default"` |
| `edges[].config` | No | Arbitrary dict passed to the edge constructor as `self.config` |

### Edge Types

| Type | Python class needed | Description |
|---|---|---|
| `direct` | No | Fixed single target — fully declared in JSON |
| `fan_out` | No | Fixed parallel targets — fully declared in JSON |
| `conditional` | Yes — extends `VsBaseConditionalEdge` | `_evaluate(state)` returns a route key; key is looked up in `route` map |
| `dynamic_fan_out` | Yes — extends `VsDynamicFanOutEdge` | `get_sends(state)` returns a list of `Send` objects for runtime branching |

---

## State

All graph state must extend `VsBaseGraphState`:

```python
from typing import Optional
from vs_graph.schema.vs_base_graph_state import VsBaseGraphState

class MyState(VsBaseGraphState):
    user_input: str
    intent: Optional[str]
    response: Optional[str]
```

`VsBaseGraphState` is a `TypedDict` providing:

| Field | Type | Description |
|---|---|---|
| `trace_id` | `str` | Auto-generated per `invoke()` call if not set. Links all trace events for this execution. |
| `error` | `Optional[VsGraphError]` | Populated by the framework when a node raises `VsUserException`. Contains `message`, `cause`, `stack_trace`. |
| `current_message` | `Optional[str]` | Convenience field for the current user-facing message. Not set by the framework. |

---

## Nodes

Extend `VsBaseNode` and implement `execute`. Decorate with `@node(name="...")` to self-register in `VsNodeRegistry`.

```python
from vs_graph.node.vs_base_node import VsBaseNode
from vs_graph.decorator.vs_node_decorator import node
from vs_graph.exception.vs_graph_exceptions import VsUserException, VsNodeExecutionException

@node(name="classifier_node")
class ClassifierNode(VsBaseNode[MyState]):

    async def execute(self, state: MyState) -> dict:
        if not state.get("user_input"):
            raise VsUserException("Input is required.")
        state["intent"] = "execute"
        await self.trace(state["trace_id"], "intent classified", data={"intent": state["intent"]})
        return state
```

### `@node` decorator

```python
@node(name="classifier_node")   # registers under key "classifier_node"
@node                           # registers under the class name
```

The `name` value must match the `"name"` field in the JSON node definition.

### What `invoke()` does (called by the graph, not you)

`VsBaseNode.invoke()` wraps your `execute()`:

1. Logs and publishes trace: `"node '{id}' started"`
2. Calls `await self.execute(state)`
3. On success: logs and publishes trace: `"node '{id}' completed"` with `duration_seconds`
4. On `VsUserException`: stores error in `state["error"]` and returns state (graph continues)
5. On `VsNodeExecutionException`: logs error and re-raises (graph stops)
6. On any other exception: logs error and re-raises (graph stops)

### Publishing trace events

```python
async def execute(self, state: MyState) -> dict:
    await self.trace(
        state["trace_id"],
        "retrieved context",
        data={"num_chunks": 8},
    )
    return state
```

`self.trace()` is a no-op if no `trace_publisher` was passed to the graph.

### Node constructor args

`VsBaseNode.__init__` receives:

| Parameter | Source |
|---|---|
| `node_id` | The `id` field from the JSON node definition |
| `config` | The `config` dict from the JSON node definition |
| `trace_publisher` | The publisher passed to `VsBaseGraph.__init__` |

Access them as `self.node_id`, `self.config`, `self.trace_publisher`.

---

## Edges

### Direct edge

No Python class. Declared fully in JSON:

```json
{ "type": "direct", "source": "executor", "target": "responder" }
```

### Fan-out edge

No Python class. Declares fixed parallel targets in JSON (minimum 2):

```json
{
  "type": "fan_out",
  "source": "splitter",
  "targets": ["worker_a", "worker_b", "worker_c"]
}
```

All targets receive the same state and execute in parallel via LangGraph's native fan-out.

### Conditional edge

Extend `VsBaseConditionalEdge` and implement `_evaluate`. Decorate with `@edge(name="...")`:

```python
from vs_graph.edge.vs_base_conditional_edge import VsBaseConditionalEdge
from vs_graph.decorator.vs_edge_decorator import edge

@edge(name="classifier_routing_edge")
class ClassifierRoutingEdge(VsBaseConditionalEdge[MyState]):

    def _evaluate(self, state: MyState) -> str:
        if state.get("intent") == "execute":
            return "execute"
        return "default"
```

`_evaluate` returns a route key. The base class's async `route()` wrapper looks it up in the `route` map from JSON, publishes the routing trace, and returns the target node id. If the key is not in the map, it falls back to `"default"`. A `"default"` entry in the JSON `route` map is required.

JSON:

```json
{
  "type": "conditional",
  "source": "classifier",
  "edge_class": "classifier_routing_edge",
  "route": {
    "execute": "executor",
    "default": "responder"
  }
}
```

### Dynamic fan-out edge

Extend `VsDynamicFanOutEdge` and implement `get_sends`. Returns a list of LangGraph `Send` objects — each specifies a target node and a custom state for that branch:

```python
from vs_graph.edge.vs_dynamic_fan_out_edge import VsDynamicFanOutEdge
from vs_graph.decorator.vs_edge_decorator import edge
from langgraph.types import Send

@edge(name="document_fan_out_edge")
class DocumentFanOutEdge(VsDynamicFanOutEdge[MyState]):

    def get_sends(self, state: MyState) -> list:
        return [
            Send("process_document", {**state, "document": doc})
            for doc in state["documents"]
        ]
```

JSON:

```json
{
  "type": "dynamic_fan_out",
  "source": "splitter",
  "edge_class": "document_fan_out_edge"
}
```

### `@edge` decorator

```python
@edge(name="classifier_routing_edge")   # registers under key "classifier_routing_edge"
@edge                                   # registers under the class name
```

The `name` value must match the `"edge_class"` field in the JSON edge definition.

---

## @graph Decorator — Auto-Import Packages

Instead of manually importing every node and edge module, use `@graph` on your graph class to declare which packages contain your implementations. The library scans and imports them automatically at `build()` time, triggering `@node` and `@edge` registration.

```python
from vs_graph.decorator.vs_graph_decorator import graph
from vs_graph.vs_base_graph import VsBaseGraph

@graph(
    nodes=["myapp.graph.nodes"],
    edges=["myapp.graph.edges"],
)
class MyGraph(VsBaseGraph[MyState]):

    def __init__(self):
        with open("my_graph.json") as f:
            graph_json = json.load(f)
        super().__init__(graph_json=graph_json, state_class=MyState)
        self.build()
```

Both `nodes` and `edges` accept a list of package paths. Each package is walked recursively — all modules within it are imported. You can specify multiple packages:

```python
@graph(
    nodes=["myapp.graph.nodes", "shared.common_nodes"],
    edges=["myapp.graph.edges"],
)
class MyGraph(VsBaseGraph[MyState]):
    ...
```

Without `@graph`, node and edge modules must be imported manually before `build()` is called:

```python
import myapp.graph.nodes.classifier_node  # noqa
import myapp.graph.nodes.executor_node    # noqa
```

`@graph` with no packages, or subclasses without the decorator, are both valid — auto-import is skipped.

---

## Registries

### VsNodeRegistry

`VsNodeRegistry` is a static registry. `@node` populates it at import time.

| Method | Description |
|---|---|
| `register(name, node_class)` | Called by `@node` — raises `ValueError` if name already registered |
| `get(name)` | Returns the class — raises `ValueError` if not found |
| `create(name, node_id, config, **kwargs)` | Instantiates the node class |
| `is_registered(name)` | Returns `True` if name is registered |
| `list_nodes()` | Returns sorted list of registered names |
| `clear()` | Removes all registered nodes — for testing only |

### VsEdgeRegistry

Same pattern as `VsNodeRegistry` for edge classes.

| Method | Description |
|---|---|
| `register(name, edge_class)` | Called by `@edge` — raises `ValueError` if name already registered |
| `get(name)` | Returns the class — raises `ValueError` if not found |
| `create(name, source, **kwargs)` | Instantiates the edge class |
| `is_registered(name)` | Returns `True` if name is registered |
| `list_edges()` | Returns sorted list of registered names |
| `clear()` | Removes all registered edges — for testing only |

---

## Checkpointer

Configured via `config.ini`. Provides LangGraph thread-level state persistence across `invoke()` calls.

```ini
[graph]
checkpointer = memory
```

```ini
[graph]
checkpointer             = redis
redis_url                = redis://localhost:6379
checkpoint_key_prefix    = vs:checkpoint:
checkpoint_ttl_seconds   = 3600
```

| Key | Default | Description |
|---|---|---|
| `graph.checkpointer` | `memory` | Checkpointer type: `memory` or `redis` |
| `graph.redis_url` | `redis://localhost:6379` | Redis connection URL (redis only) |
| `graph.checkpoint_key_prefix` | `vs:checkpoint:` | Key prefix for stored checkpoints (redis only) |
| `graph.checkpoint_ttl_seconds` | None | TTL for checkpoint keys in seconds (redis only) |

Custom checkpointers can be registered via `VsCheckpointerFactory`:

```python
from vs_graph.checkpointer.vs_checkpointer_factory import VsCheckpointerFactory

VsCheckpointerFactory.register(
    "postgres",
    lambda cfg: MyPostgresCheckpointer(config=cfg)
)
```

The factory lambda receives the same `cfg` dict that `_load_checkpointer` builds from `config.ini`.

---

## Trace Publisher

Pass a `VsBaseTracePublisher` to the graph constructor to stream execution events to any external sink (queue, websocket, database):

```python
from vs_common.publisher.vs_base_trace_publisher import VsBaseTracePublisher
from vs_common.schema.vs_trace_level import VsTraceLevel
from typing import Any, Dict, Optional

class MyTracePublisher(VsBaseTracePublisher):

    async def publish(
        self,
        trace_id: str,
        message: str,
        level: VsTraceLevel = VsTraceLevel.INFO,
        data: Optional[Dict[str, Any]] = None,
    ) -> None:
        await my_queue.push({
            "trace_id": trace_id,
            "message": message,
            "level": level.value,
            "data": data or {},
        })
```

```python
graph = MyGraph(graph_json, state_class=MyState, trace_publisher=MyTracePublisher())
```

The publisher is automatically propagated to every node and edge instance. You do not pass it to nodes or edges directly.

**Events published automatically by the framework:**

| Event | Source |
|---|---|
| `"node '{id}' started"` | `VsBaseNode.invoke()` |
| `"node '{id}' completed"` with `duration_seconds` | `VsBaseNode.invoke()` |
| `"node '{id}' user error"` | `VsBaseNode.invoke()` on `VsUserException` |
| `"node '{id}' failed"` | `VsBaseNode.invoke()` on exception |
| `"edge '{source}' routing to '{next_node}'"` with `route_key`, `next_node`, `duration_seconds` | `VsBaseConditionalEdge.route()` |
| `"edge '{source}' fanning out to {n} branch(es)"` with `branch_count`, `targets`, `duration_seconds` | `VsDynamicFanOutEdge.route()` |

Direct and static `fan_out` edges are pure topology — they compile to plain LangGraph edges and emit no trace events. The routing wrappers are `async` and `await` the trace publish before returning the next node, so the routing event is always ordered ahead of the next node's `"started"` event.

---

## Exceptions

| Exception | When to raise | Effect |
|---|---|---|
| `VsUserException` | Error is safe to surface to the user | Stored in `state["error"]` — graph continues to next node |
| `VsNodeExecutionException` | Internal node failure | Logged and re-raised — graph stops |
| `VsGraphBuildException` | Invalid build state | Raised during `build()` |
| `VsEdgeEvaluationException` | Edge routing failure | Raised from edge `evaluate()` |

```python
from vs_graph.exception.vs_graph_exceptions import VsUserException, VsNodeExecutionException

async def execute(self, state: MyState) -> dict:
    if not state.get("user_input"):
        raise VsUserException("Please provide an input.")

    try:
        result = await call_external_service()
    except Exception as e:
        raise VsNodeExecutionException(f"External service failed: {e}") from e

    state["result"] = result
    return state
```

`state["error"]` shape when `VsUserException` is raised:

```json
{
  "message": "Please provide an input.",
  "cause": null,
  "stack_trace": null
}
```

---

## Full Example

```python
import json
from typing import Optional

from vs_graph.vs_base_graph import VsBaseGraph
from vs_graph.schema.vs_base_graph_state import VsBaseGraphState
from vs_graph.node.vs_base_node import VsBaseNode
from vs_graph.edge.vs_base_conditional_edge import VsBaseConditionalEdge
from vs_graph.decorator.vs_node_decorator import node
from vs_graph.decorator.vs_edge_decorator import edge
from vs_graph.decorator.vs_graph_decorator import graph
from vs_graph.exception.vs_graph_exceptions import VsUserException


# --- State ---

class MyState(VsBaseGraphState):
    user_input: str
    intent: Optional[str]
    response: Optional[str]


# --- Nodes ---

@node(name="classifier_node")
class ClassifierNode(VsBaseNode[MyState]):

    async def execute(self, state: MyState) -> dict:
        if not state.get("user_input"):
            raise VsUserException("Input is required.")
        state["intent"] = "search" if "find" in state["user_input"] else "chat"
        await self.trace(state["trace_id"], "classified", data={"intent": state["intent"]})
        return state


@node(name="responder_node")
class ResponderNode(VsBaseNode[MyState]):

    async def execute(self, state: MyState) -> dict:
        state["response"] = f"Handling intent: {state['intent']}"
        return state


# --- Edges ---

@edge(name="classifier_routing_edge")
class ClassifierRoutingEdge(VsBaseConditionalEdge[MyState]):

    def _evaluate(self, state: MyState) -> str:
        return state.get("intent", "default")


# --- Graph ---

@graph(nodes=["myapp.graph.nodes"], edges=["myapp.graph.edges"])
class MyGraph(VsBaseGraph[MyState]):

    def __init__(self):
        graph_json = {
            "version": "1.0",
            "name": "my_graph",
            "entry_node": "classifier",
            "exit_nodes": ["responder"],
            "nodes": [
                {"id": "classifier", "name": "classifier_node", "config": {}},
                {"id": "responder",  "name": "responder_node",  "config": {}},
            ],
            "edges": [
                {
                    "type": "conditional",
                    "source": "classifier",
                    "edge_class": "classifier_routing_edge",
                    "route": {"search": "responder", "chat": "responder", "default": "responder"}
                }
            ]
        }
        super().__init__(graph_json=graph_json, state_class=MyState)
        self.build()


# --- Run ---

import asyncio

async def main():
    g = MyGraph()
    result = await g.invoke({
        "trace_id": "",
        "error": None,
        "current_message": None,
        "user_input": "find me a product",
        "intent": None,
        "response": None,
    })
    print(result["response"])  # Handling intent: search

asyncio.run(main())
```

---

## Class Reference

---

### VsBaseGraph

Abstract base class for all graphs. Extend it and call `build()` in `__init__`.

**Constructor:**

| Parameter | Type | Description |
|---|---|---|
| `graph_json` | `Dict[str, Any]` | Parsed graph JSON — validated on construction |
| `state_class` | `Type[S]` | TypedDict subclass used as LangGraph state type |
| `trace_publisher` | `Optional[VsBaseTracePublisher]` | Publisher injected into all nodes and edges |

**Methods:**

| Method | Description |
|---|---|
| `build()` | Auto-imports packages, instantiates nodes/edges, validates, loads checkpointer, compiles LangGraph. Call once at startup. |
| `async invoke(state, config=None)` | Runs the compiled graph. Auto-generates `trace_id` if not set. |

---

### VsBaseNode

Abstract base class for all nodes.

**Constructor parameters** (injected by `VsNodeRegistry.create()`):

| Parameter | Type | Description |
|---|---|---|
| `node_id` | `str` | Node id from JSON |
| `config` | `Optional[Dict[str, Any]]` | Node config dict from JSON |
| `trace_publisher` | `Optional[VsBaseTracePublisher]` | Propagated from the graph |

**Instance attributes:**

| Attribute | Description |
|---|---|
| `self.node_id` | The node id from JSON |
| `self.config` | The config dict from JSON |
| `self.trace_publisher` | The graph-level trace publisher |
| `self.logger` | Logger instance keyed to the class name |

**Abstract method:**

| Method | Signature | Description |
|---|---|---|
| `execute` | `async execute(state: S) -> dict` | Implement your node logic here. Return the updated state dict. |

**Helper method:**

| Method | Signature | Description |
|---|---|---|
| `trace` | `async trace(trace_id, message, data=None, level=INFO)` | Publishes a trace event. No-op if no publisher. |

---

### VsBaseConditionalEdge

Abstract base class for conditional routing edges.

**Constructor parameters:**

| Parameter | Type | Description |
|---|---|---|
| `source` | `str` | Source node id |
| `route` | `Dict[str, str]` | Map of route keys to target node ids — must include `"default"`. Stored as `self.route_map`. |
| `config` | `Optional[Dict[str, Any]]` | Edge config dict from JSON |
| `trace_publisher` | `Optional[VsBaseTracePublisher]` | Propagated from the graph |

**Abstract method:**

| Method | Signature | Description |
|---|---|---|
| `_evaluate` | `_evaluate(state: S) -> str` | Return a route key. `route()` looks it up in `route_map`; falls back to `"default"`. |

**Routing function** (registered with LangGraph — you do not call it):

| Method | Signature | Description |
|---|---|---|
| `route` | `async route(state: S) -> str` | Calls `_evaluate`, resolves the key against `route_map` (falling back to `"default"`), publishes the routing trace, returns the target node id. Raises if there is no default. |

---

### VsDynamicFanOutEdge

Abstract base class for runtime fan-out edges.

**Abstract method:**

| Method | Signature | Description |
|---|---|---|
| `get_sends` | `get_sends(state: S) -> List` | Return a list of `langgraph.types.Send` objects. Each `Send` specifies a target node and a custom state dict for that branch. |

**Routing function** (registered with LangGraph — you do not call it):

| Method | Signature | Description |
|---|---|---|
| `route` | `async route(state: S) -> List` | Calls `get_sends`, publishes a fan-out trace with `branch_count` and `targets`, returns the `Send` list. |

---

### VsCheckpointerFactory

Static factory for checkpointer registration and creation.

| Method | Description |
|---|---|
| `register(name, factory_fn)` | Register a custom checkpointer. `factory_fn` receives a config dict. |
| `create(checkpointer_type, config)` | Instantiate and return the checkpointer. |

Built-in types: `"memory"`, `"redis"`.

---

## Running Tests

```bash
./run_tests.sh
```
