# 05. (ConversationKGMemory)

## ConversationKGMemory <a href="#conversationkgmemory" id="conversationkgmemory"></a>

Leverage the power of knowledge graphs to store and retrieve information.

This helps the model understand relationships between different entities, and improves its ability to respond based on complex networks and historical context.

```
# API KEY A configuration file for managing environment variables
from dotenv import load_dotenv

# API KEY Load information
load_dotenv()
```

```
True
```

```
from langchain_openai import ChatOpenAI
from langchain.memory import ConversationKGMemory
```

```
llm = ChatOpenAI(temperature=0)

memory = ConversationKGMemory(llm=llm, return_messages=True)
memory.save_context(
    {"input": "This is Pangyo My name is Shirley Kim, and I live in."},
    {"output": "Who is Kim Shirley?"},
)
memory.save_context(
    {"input": "Kim Shirley is our company's new designer."},
    {"output": "nice to meet you."},
)
```

```
memory.load_memory_variables({"input": "Who is Kim Shirley?"})
```

```
{'history': [SystemMessage(content='On Pangyo: Pangyo has resident Kim Shirley.'),  SystemMessage(content='On Kim Shirley: Kim Shirley is a new designer. Kim Shirley is in our company.')]}
```

### Utilizing memory in Chain

```
from langchain.prompts.prompt import PromptTemplate
from langchain.chains import ConversationChain

llm = ChatOpenAI(temperature=0)

template = """The following is a friendly conversation between a human and an AI. 
The AI is talkative and provides lots of specific details from its context. 
If the AI does not know the answer to a question, it truthfully says it does not know. 
The AI ONLY uses information contained in the "Relevant Information" section and does not hallucinate.

Relevant Information:

{history}

Conversation:
Human: {input}
AI:"""
prompt = PromptTemplate(
    input_variables=["history", "input"], template=template)

conversation_with_kg = ConversationChain(
    llm=llm, prompt=prompt, memory=ConversationKGMemory(llm=llm)
)
```

Let's start the first conversation. Let's give some basic information about the character.

```
conversation_with_kg.predict(
    input="My name is Teddy. Shirley is a coworker of mine, and she's a new designer at our company."
)
```

```
"Hello Teddy! It's nice to meet you. Shirley must be excited to be starting a new job as a designer at your company. I hope she's settling in well and getting to know her new colleagues. If you need any tips on how to make her feel welcome or help her adjust to the new role, feel free to ask me!"
```

We're going to ask questions about a person named Shirley.

```
# Question about shirley 
conversation_with_kg.memory.load_memory_variables({"input": "who is Shirley?"})
```

```
{'history': 'On Shirley: Shirley is a coworker. Shirley is a new designer. Shirley is at company.'}
```
