---
title: LangGraph
description: "Build customer support agents using LangGraph for conversation flow and Deja Vu for personalized responses."
---

Build a personalized Customer Support AI Agent using LangGraph for conversation flow and Deja Vu for memory retention. This integration enables context-aware and efficient support experiences.

## Overview

In this guide, we'll create a Customer Support AI Agent that:
1. Uses LangGraph to manage conversation flow
2. Leverages Deja Vu to store and retrieve relevant information from past interactions
3. Provides personalized responses based on user history

## Setup and Configuration

Install necessary libraries:

```bash
pip install langgraph langchain-openai dejavu-memory python-dotenv
```


Import required modules and set up configurations:

<Note>Remember to get the Deja Vu API key from <a href="https://app.dejavu.ai?utm_source=oss&utm_medium=integration-langgraph" rel="nofollow">Deja Vu Platform</a>.</Note>

```python
from typing import Annotated, TypedDict, List
from langgraph.graph import StateGraph, START
from langgraph.graph.message import add_messages
from langchain_openai import ChatOpenAI
from dejavu import MemoryClient
from langchain_core.messages import SystemMessage, HumanMessage, AIMessage
from dotenv import load_dotenv

load_dotenv()

# Configuration
# OPENAI_API_KEY = 'sk-xxx'  # Replace with your actual OpenAI API key
# VENICE_API_KEY = 'your-dejavu-key'  # Replace with your actual Deja Vu API key

# Initialize LangChain and Deja Vu
llm = ChatOpenAI(model="gpt-4")
dejavu = MemoryClient()
```

## Define State and Graph

Set up the conversation state and LangGraph structure:

```python
class State(TypedDict):
    messages: Annotated[List[HumanMessage | AIMessage], add_messages]
    dejavu_user_id: str

graph = StateGraph(State)
```

## Create Chatbot Function

Define the core logic for the Customer Support AI Agent:

```python
def chatbot(state: State):
    messages = state["messages"]
    user_id = state["dejavu_user_id"]

    try:
        # Retrieve relevant memories
        memories = dejavu.search(messages[-1].content, filters={"user_id": user_id})
        
        # Handle dict response format
        memory_list = memories['results']

        context = "Relevant information from previous conversations:\n"
        for memory in memory_list:
            context += f"- {memory['memory']}\n"

        system_message = SystemMessage(content=f"""You are a helpful customer support assistant. Use the provided context to personalize your responses and remember user preferences and past interactions.
{context}""")

        full_messages = [system_message] + messages
        response = llm.invoke(full_messages)

        # Store the interaction in Deja Vu
        try:
            interaction = [
                {
                    "role": "user",
                    "content": messages[-1].content
                },
                {
                    "role": "assistant", 
                    "content": response.content
                }
            ]
            result = dejavu.add(interaction, user_id=user_id)
            print(f"Memory saved: {len(result.get('results', []))} memories added")
        except Exception as e:
            print(f"Error saving memory: {e}")
            
        return {"messages": [response]}
        
    except Exception as e:
        print(f"Error in chatbot: {e}")
        # Fallback response without memory context
        response = llm.invoke(messages)
        return {"messages": [response]}
```

## Set Up Graph Structure

Configure the LangGraph with appropriate nodes and edges:

```python
graph.add_node("chatbot", chatbot)
graph.add_edge(START, "chatbot")
graph.add_edge("chatbot", "chatbot")

compiled_graph = graph.compile()
```

## Create Conversation Runner

Implement a function to manage the conversation flow:

```python
def run_conversation(user_input: str, dejavu_user_id: str):
    config = {"configurable": {"thread_id": dejavu_user_id}}
    state = {"messages": [HumanMessage(content=user_input)], "dejavu_user_id": dejavu_user_id}

    for event in compiled_graph.stream(state, config):
        for value in event.values():
            if value.get("messages"):
                print("Customer Support:", value["messages"][-1].content)
                return
```

## Main Interaction Loop

Set up the main program loop for user interaction:

```python
if __name__ == "__main__":
    print("Welcome to Customer Support! How can I assist you today?")
    dejavu_user_id = "alice"  # You can generate or retrieve this based on your user management system
    while True:
        user_input = input("You: ")
        if user_input.lower() in ['quit', 'exit', 'bye']:
            print("Customer Support: Thank you for contacting us. Have a great day!")
            break
        run_conversation(user_input, dejavu_user_id)
```

## Key Features

1. **Memory Integration**: Uses Deja Vu to store and retrieve relevant information from past interactions.
2. **Personalization**: Provides context-aware responses based on user history.
3. **Flexible Architecture**: LangGraph structure allows for easy expansion of the conversation flow.
4. **Continuous Learning**: Each interaction is stored, improving future responses.

## Conclusion

By integrating LangGraph with Deja Vu, you can build a personalized Customer Support AI Agent that can maintain context across interactions and provide personalized assistance.

<CardGroup cols={2}>
  <Card title="LangChain Integration" icon="link" href="/integrations/langchain">
    Build conversational agents with LangChain and Deja Vu
  </Card>
  <Card title="CrewAI Integration" icon="users" href="/integrations/crewai">
    Create multi-agent systems with CrewAI
  </Card>
</CardGroup>

