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

# LangGraph

> Learn how to integrate KeywordsAI tracing with Vercel AI SDK to monitor and analyze your AI application performance. Step-by-step guide for setting up environment variables and creating traced workflows.

We integrated LangGraph into Keywords AI so that you can use it with our tracing feature. In this guide, you will know how to run your graph and our tracer will automatically keep track of everything that happens in chronological order in this graph run.

<Steps>
  <Step title="Import LangGraph dependencies">
    ```python Python theme={"system"}
    from typing import Annotated
    from typing_extensions import TypedDict
    from langgraph.graph import StateGraph, START, END
    from langgraph.graph.message import add_messages

    # Initialize the State for langgraph
    class State(TypedDict):
        # Messages have the type "list". The `add_messages` function
        # in the annotation defines how this state key should be updated
        # (in this case, it appends messages to the list, rather than overwriting them)
        messages: Annotated[list, add_messages]


    graph_builder = StateGraph(State)
    ```
  </Step>

  <Step title="Initialize the LLM">
    ```python Python theme={"system"}
    from langchain_anthropic import ChatAnthropic

    llm = ChatAnthropic(model="claude-3-5-sonnet-20240620", temperature=0)
    ```
  </Step>

  <Step title="Add the LLM node to the graph">
    ```python Python theme={"system"}
    from keywordsai_tracing.main import KeywordsAITelemetry
    from keywordsai_tracing.decorators import task, workflow
    ktl = KeywordsAITelemetry()
    ```
  </Step>

  <Step title="Define the chatbot function and wrap it with the tracing decorator">
    ```python Python theme={"system"}
    @task(name="chatbot_response")
    def chatbot_respond(state: State):
        return {"messages": [llm.invoke(state["messages"])]}
    ```
  </Step>

  <Step title="Setup the node and edges">
    ```python Python theme={"system"}
    graph_builder.add_node("chatbot", chatbot_respond)
    graph_builder.add_edge(START, "chatbot")
    graph_builder.add_edge("chatbot", END)
    graph = graph_builder.compile()
    ```
  </Step>

  <Step title="Define the stream_graph_updates function">
    ```python Python theme={"system"}
    def stream_graph_updates(user_input: str):
        for event in graph.stream({"messages": [{"role": "user", "content": user_input}]}):
            for value in event.values():
                print("Assistant:", value["messages"][-1].content)
    ```
  </Step>

  <Step title="Define the user_send_message function">
    ```python Python theme={"system"}
    @task(name="user_send_message")
    def user_send_message() -> str:
        input_message = input("User: ")
        return input_message
    ```
  </Step>

  <Step title="Wrap everything in a workflow">
    ```python Python theme={"system"}
    @workflow(name="chatbot_qa")
    def chatbot_qa():
        while True:
            try:
                user_input = user_send_message()
                if user_input.lower() in ["quit", "exit", "q"]:
                    print("Goodbye!")
                    break

                stream_graph_updates(user_input)
            except:
                # fallback if input() is not available
                user_input = "What do you know about LangGraph?"
                print("User: " + user_input)
                stream_graph_updates(user_input)
                break
    ```
  </Step>

  <Step title="Run the workflow">
    ```python Python theme={"system"}
    if __name__ == "__main__":
        chatbot_qa()
    ```
  </Step>
</Steps>
