> ## Documentation Index
> Fetch the complete documentation index at: https://genai.codewithsiva.dev/llms.txt
> Use this file to discover all available pages before exploring further.

# Graph III: Sequential Graph

> Connect multiple nodes sequentially to transform state step-by-step

In this section, we will build a sequential graph where data flows through multiple nodes, and each node updates a specific part of the shared state.

## Objectives

1. Create multiple nodes that sequentially process and update different parts of the state.
2. Connect nodes together using normal edges.
3. Invoke the graph and see how the state is transformed step-by-step.

## Graph III: Sequential Graph

#### Goal

Build a sequential graph where data flows through multiple nodes, and each node updates a specific part of the shared state.

#### Sample Input

```python theme={null}
{"name": "Chirag", "age": 20}
```

#### Sample Output

```python theme={null}
{"name": "Chirag", "age": 20, "final": "Hi Chirag! You are 20 years old!"}
```

#### Plan

1. Define the state schema (`AgentState`) with `name`, `age`, and `final` variables.
2. Define two node functions: `first_node` (to set greeting) and `second_node` (to append age description).
3. Build, connect sequentially using normal edges, and compile the graph.
4. Invoke the graph and view the final result.

### Code Implementation

#### 1. Define the State Schema

We define the state structure. Notice that `final` will be used as a combined output accumulator:

```python theme={null}
from typing import TypedDict

class AgentState(TypedDict):
    name: str
    age: str
    final: str
```

#### 2. Define the Nodes

We define two nodes. The first node sets the greeting using the name, and the second node appends the age explanation:

```python theme={null}
def first_node(state: AgentState) -> AgentState:
    state["final"] = f"Hi {state['name']}!"
    return state

def second_node(state: AgentState) -> AgentState:
    state["final"] = state["final"] + f" You are {state['age']} years old!"
    return state
```

#### 3. Create and Compile the Graph

We add both nodes, connect them using `add_edge`, and compile the graph:

```python theme={null}
from langgraph.graph import StateGraph

graph = StateGraph(AgentState)

# Add both nodes
graph.add_node("first_node", first_node)
graph.add_node("second_node", second_node)

# Define the flow
graph.set_entry_point("first_node")
graph.add_edge("first_node", "second_node")
graph.set_finish_point("second_node")

app = graph.compile()
```

#### 4. Invoke the Graph

Pass the name and age to retrieve the final compiled string:

```python theme={null}
answers = app.invoke({"name": "Chirag", "age": 20})
print(answers["final"])
# Output: Hi Chirag! You are 20 years old!
```

## Exercise: Three-Node Sequential Agent 💪

#### Goal

Connect three nodes sequentially to customize a greeting, display the user's age, and format a list of their skills.

#### Sample Input

```python theme={null}
{
    "name": "Deepa",
    "age": 31,
    "skills": ["Python", "Machine Learning", "LangGraph"]
}
```

#### Sample Output

```python theme={null}
"Deepa, welcome to the system! You are 31 years old! You have skills in:
Python, Machine Learning, and LangGraph"
```

#### Plan

1. Define an `AgentState` containing `name` (str), `age` (int), `skills` (list of strings), and `result` (str) fields.
2. Create `greeting_node` (to greet), `age_node` (to append age description), and `skills_node` (to join skills with commas and 'and', appending them to the result).
3. Build the graph, register all three nodes, connect them in order (`greeting` -> `age` -> `skills`), set entry/finish points, compile and run.

<Accordion title="Solution">
  ```python theme={null}
  from typing import TypedDict
  from langgraph.graph import StateGraph

  # 1. State Schema
  class AgentState(TypedDict):
      name: str
      age: int
      skills: list[str]
      result: str

  # 2. Node Functions
  def greeting_node(state: AgentState) -> AgentState:
      state["result"] = f"{state['name']}, welcome to the system!"
      return state

  def age_node(state: AgentState) -> AgentState:
      state["result"] += f" You are {state['age']} years old!"
      return state

  def skills_node(state: AgentState) -> AgentState:
      skills_str = ", ".join(state["skills"][:-1]) + ", and " + state["skills"][-1]
      state["result"] += f" You have skills in:\n{skills_str}"
      return state

  # 3. Create Graph
  graph = StateGraph(AgentState)
  graph.add_node("greeting", greeting_node)
  graph.add_node("age", age_node)
  graph.add_node("skills", skills_node)

  graph.set_entry_point("greeting")
  graph.add_edge("greeting", "age")
  graph.add_edge("age", "skills")
  graph.set_finish_point("skills")

  # 4. Compile and Run
  app = graph.compile()
  output = app.invoke({
      "name": "Deepa",
      "age": 31,
      "skills": ["Python", "Machine Learning", "LangGraph"]
  })
  print(output["result"])
  ```
</Accordion>

## Practice & Exercises

To reinforce what you've learned in this section (sequential node execution and data transformation), practice with the interactive notebook:

<CardGroup cols={1}>
  <Card title="Practice & Exercises" icon="laptop-code">
    Practice defining multiple sequential nodes, linking them with edges, and building a sequential agent.

    [💻 VS Code](vscode://file/Users/sivaprasad/Downloads/GenAI%20With%20Python/public/notebooks/langgraph/Graph3_Sequential.ipynb) | [🚀 Colab](https://colab.research.google.com/github/prasad230776/genai-course/blob/master/public/notebooks/langgraph/Graph3_Sequential.ipynb) | <a href="/public/notebooks/langgraph/Graph3_Sequential.ipynb" download>📥 Download</a>
  </Card>
</CardGroup>
