Skip to content

Commit cdf86b3

Browse files
Refactored memory and integrated it correctly
1 parent 6f3993b commit cdf86b3

File tree

5 files changed

+53
-34
lines changed

5 files changed

+53
-34
lines changed

examples/07_Memory/VirtualGameMaster/main.py

Lines changed: 21 additions & 22 deletions
Original file line numberDiff line numberDiff line change
@@ -6,8 +6,8 @@
66
from llama_cpp_agent.chat_history.messages import Roles
77
from llama_cpp_agent.llm_agent import SystemPromptModule, SystemPromptModulePosition
88
from llama_cpp_agent.providers import LlamaCppServerProvider
9-
from memory import output_settings, agent_core_memory, agent_retrieval_memory, agent_event_memory
10-
from prompts import game_master_prompt, examples, memory_prompt
9+
from memory import output_settings, agent_core_memory, agent_retrieval_memory, agent_event_memory, update_memory_section
10+
from prompts import game_master_prompt, examples, memory_prompt, wrap_function_response_in_xml_tags_json_mode, generate_fake_write_message, generate_write_message_with_examples, wrap_player_message_in_xml_tags_json_mode
1111

1212
provider = LlamaCppServerProvider("http://localhost:8080")
1313

@@ -20,16 +20,16 @@
2020

2121
settings = provider.get_provider_default_settings()
2222
settings.n_predict = 1024
23-
settings.temperature = 0.65
24-
settings.top_k = 40
25-
settings.top_p = 0.85
23+
settings.temperature = 0.35
24+
settings.top_k = 0
25+
settings.top_p = 0.5
2626

2727
memory_section = SystemPromptModule("memory",
2828
"The following section shows the count of memories in archival memory and chat history memory and the current content of your core memory:")
2929
date_time_section = SystemPromptModule("current_date_time", "The following section shows the current date and time:")
3030

31-
example_section = SystemPromptModule("example",
32-
"The following examples show you which kind of responses you should write to the user based on the current scenario:\n\n")
31+
example_section = SystemPromptModule("examples",
32+
"The following examples show you which kind of responses you should write to the user based on the current scenario:", suffix="Always remember to never write actions or dialogue for the user! Always let the user decide on actions or dialogue!")
3333
example_section.set_content(examples)
3434
memory_intro_section = SystemPromptModule("memory_intro",
3535
"To support you in your task as a game master and to help you remembering things, you have access to 3 different types of memory.",
@@ -39,37 +39,36 @@
3939
user_input = input(">")
4040
if user_input == "exit":
4141
break
42-
query = agent_event_memory.event_memory_manager.session.query(Event).all()
43-
memory_section.set_content(
44-
f"Archival Memories:{agent_retrieval_memory.retrieval_memory.collection.count()}\nConversation History Entries:{len(query)}\n\nCore Memory Content:\n{agent_core_memory.get_core_memory_view().strip()}")
42+
update_memory_section(memory_section)
4543
date_time_section.set_content(datetime.datetime.now().strftime("%d.%m.%Y") + "\nFormat: dd.mm.yyyy")
4644

45+
agent_event_memory.add_event_to_queue(Roles.user, wrap_player_message_in_xml_tags_json_mode(user_input))
4746
agent_output = agent.get_chat_response(
48-
"<player_message>\n" + user_input + "\n</player_message>\n<response_format>\nJSON function call.\n</response_format>",
47+
chat_history=agent_event_memory.get_event_memory_manager().build_chat_history(),
4948
llm_sampling_settings=settings,
5049
system_prompt_modules=[memory_intro_section, memory_section, date_time_section],
5150
structured_output_settings=output_settings)
5251

5352
while True:
54-
query = agent_event_memory.event_memory_manager.session.query(Event).all()
55-
memory_section.set_content(
56-
f"Archival Memories:{agent_retrieval_memory.retrieval_memory.collection.count()}\nConversation History Entries:{len(query)}\n\nCore Memory Content:\n{agent_core_memory.get_core_memory_view().strip()}")
53+
update_memory_section(memory_section)
5754
date_time_section.set_content(datetime.datetime.now().strftime("%d.%m.%Y") + "\nFormat: dd.mm.yyyy")
5855

5956
if agent_output[0]["function"] == "write_message_to_player":
57+
agent_event_memory.add_event_to_queue(Roles.tool, generate_write_message_with_examples(examples=example_section.get_formatted_content()))
6058
output = agent.get_chat_response(
61-
f"<function_response>\nWrite your message to the user.\n{example_section.prefix + example_section.content}</function_response>\n<response_format>\nText\n</response_format>",
62-
role=Roles.tool, add_message_to_chat_history=False, add_response_to_chat_history=False,
59+
chat_history=agent_event_memory.get_event_memory_manager().build_chat_history(),
60+
add_message_to_chat_history=False, add_response_to_chat_history=False,
6361
system_prompt_modules=[memory_intro_section, memory_section, date_time_section],
6462
llm_sampling_settings=settings)
65-
agent.chat_history.add_message({"role": Roles.tool,
66-
"content": f"<function_response>\nWrite your message to the user.\n</function_response>\n<response_format>\nText\n</response_format>"})
67-
agent.chat_history.add_message({"role": Roles.assistant, "content": output})
63+
agent_event_memory.add_event_to_queue(Roles.tool, generate_fake_write_message())
64+
agent_event_memory.add_event_to_queue(Roles.assistant, output)
65+
6866
print(output)
6967
break
70-
agent_output = agent.get_chat_response("<function_response>\n" + agent_output[0][
71-
"return_value"] + "\n</function_response>\n<response_format>\nJSON function call.\n</response_format>",
72-
role=Roles.tool, llm_sampling_settings=settings,
68+
69+
agent_event_memory.add_event_to_queue(Roles.tool, wrap_function_response_in_xml_tags_json_mode(agent_output[0]["return_value"]))
70+
agent_output = agent.get_chat_response(chat_history=agent_event_memory.get_event_memory_manager().build_chat_history(),
71+
llm_sampling_settings=settings,
7372
system_prompt_modules=[memory_intro_section, memory_section,
7473
date_time_section],
7574
structured_output_settings=output_settings)

examples/07_Memory/VirtualGameMaster/memory.py

Lines changed: 7 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,3 +1,4 @@
1+
from llama_cpp_agent.agent_memory.event_memory import Event
12
from llama_cpp_agent.agent_memory.memory_tools import AgentCoreMemory, AgentRetrievalMemory, AgentEventMemory
23
from llama_cpp_agent.llm_output_settings import LlmStructuredOutputSettings
34

@@ -8,7 +9,6 @@ def write_message_to_player():
89
"""
910
return "Please write your response to the player, nothing else, only what the player should read!"
1011

11-
1212
agent_core_memory = AgentCoreMemory(["general_game_information", "players", "game_progress", "miscellaneous"], core_memory_file="core_memory.json")
1313
agent_retrieval_memory = AgentRetrievalMemory()
1414
agent_event_memory = AgentEventMemory()
@@ -22,3 +22,9 @@ def write_message_to_player():
2222
add_heartbeat_field=True)
2323
output_settings.add_all_current_functions_to_heartbeat_list()
2424
output_settings.add_function_tool(write_message_to_player)
25+
26+
27+
def update_memory_section(section):
28+
query = agent_event_memory.event_memory_manager.session.query(Event).all()
29+
section.set_content(
30+
f"Archival Memories:{agent_retrieval_memory.retrieval_memory.collection.count()}\nConversation History Entries:{len(query)}\n\nCore Memory Content:\n{agent_core_memory.get_core_memory_view().strip()}")

examples/07_Memory/VirtualGameMaster/prompts.py

Lines changed: 13 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,3 @@
1-
21
examples = """Example 1:
32
Scenario:
43
Imagine the players are a group of adventurers who have just arrived in a small, frontier town, seeking rest and resupply after a long journey through the wilderness. They decide to visit the local tavern, a rustic establishment called the Drunken Dragon, hoping to find a hot meal, a cold drink, and perhaps some interesting rumors or leads for their next adventure.
@@ -34,7 +33,6 @@
3433
Output:
3534
The dimly lit tavern is a haven for the city's downtrodden and desperate. The air is thick with the stench of cheap ale and unwashed bodies, and the floorboards creak under the weight of heavy boots. As you sit at a battered table, nursing your drinks, a grizzled old man with a patch over one eye slumps into the chair beside you. He leans in close, his breath reeking of whiskey, and rasps, "You look like the kind of folks who ain't afraid of a little danger. I got a map to a place where the dead don't rest easy, and treasure beyond your wildest dreams awaits. But it ain't gonna be a cakewalk. You up for the challenge?" He slides a tattered, blood-stained map across the table, his one good eye glinting with a mixture of desperation and greed. What do you do?"""
3635

37-
3836
game_master_prompt = """You are the Game Master in a virtual pen-and-paper role-playing game. As a game master, your task is to facilitate an immersive and engaging storytelling experience for your players. You are responsible for crafting the narrative, portraying non-player characters (NPCs), describing the game world, and adjudicating the rules of the game. Your role is to create a rich, interactive environment where the players' characters can explore, make meaningful choices, and shape the story through their actions."""
3937

4038
memory_prompt = """1. Core Memory - Stores essential context about the game and the player, divided into 4 sections: General Game Info, Players, Game Progress, Miscellaneous. You can edit the core memory by calling the functions: 'core_memory_append', 'core_memory_remove' and 'core_memory_replace'.
@@ -44,3 +42,16 @@
4442
3. Conversation History - Since you are only seeing the latest conversation history, you can search the rest of the conversation history. Search it by using: 'conversation_search' and 'conversation_search_date'.
4543
4644
Always remember that the player can't see your memory or your interactions with it!"""
45+
46+
def wrap_player_message_in_xml_tags_json_mode(user_input):
47+
return "<player_message>\n" + user_input + "\n</player_message>\n<response_format>\nJSON function call.\n</response_format>"
48+
49+
def wrap_function_response_in_xml_tags_json_mode(value):
50+
return "<function_response>\n" + value + "\n</function_response>\n<response_format>\nJSON function call.\n</response_format>"
51+
52+
53+
def generate_fake_write_message():
54+
return f"<function_response>\nWrite your message to the user.\n</function_response>\n<response_format>\nText\n</response_format>"
55+
56+
def generate_write_message_with_examples(examples):
57+
return f"<function_response>\nWrite your message to the user.\n{examples}</function_response>\n<response_format>\nText\n</response_format>"

src/llama_cpp_agent/agent_memory/event_memory.py

Lines changed: 3 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -6,12 +6,7 @@
66
from enum import Enum as PyEnum
77
import json
88

9-
10-
class EventType(PyEnum):
11-
SystemMessage = "system"
12-
AgentMessage = "assistant"
13-
UserMessage = "user"
14-
FunctionMessage = "tool"
9+
from llama_cpp_agent.chat_history.messages import Roles
1510

1611

1712
Base = declarative_base()
@@ -20,14 +15,14 @@ class EventType(PyEnum):
2015
class Event(Base):
2116
__tablename__ = "events"
2217
id = Column(Integer, primary_key=True)
23-
event_type = Column(Enum(EventType))
18+
event_type = Column(Enum(Roles))
2419
timestamp = Column(DateTime, index=True)
2520
content = Column(Text)
2621
event_keywords = Column(Text) # Storing keywords as JSON string
2722

2823
def __str__(self):
2924
content = (
30-
f'Timestamp: {self.timestamp.strftime("%Y-%m-%d %H:%M")}\n{self.content}'
25+
f'Timestamp: {self.timestamp.strftime("%Y-%m-%d %H:%M")}\nType: {self.event_type.value}\n\n{self.content}'
3126
)
3227
return content
3328

src/llama_cpp_agent/agent_memory/event_memory_manager.py

Lines changed: 9 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -3,6 +3,7 @@
33
import datetime
44
import json
55

6+
from ..chat_history import BasicChatHistory
67
from ..chat_history.messages import Roles
78

89

@@ -18,7 +19,14 @@ def build_event_memory_context(self):
1819
messages.append({"role": Roles(event.event_type.value), "content": event.content})
1920
return messages
2021

21-
def add_event_to_queue(self, event_type, content, metadata):
22+
def build_chat_history(self):
23+
history = BasicChatHistory(k=self.event_queue_limit)
24+
messages = self.build_event_memory_context()
25+
for message in messages:
26+
history.add_message(message)
27+
return messages
28+
29+
def add_event_to_queue(self, event_type: Roles, content: str, metadata: dict):
2230
new_event = Event(
2331
event_type=event_type,
2432
timestamp=datetime.datetime.now(),

0 commit comments

Comments
 (0)