Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
Add synchronous memgpt agent (#156)
Vivian Fang53cacad075f3
diff --git a/memgpt/agent.py b/memgpt/agent.pyindex 85ce0df31..bef024d36 100644--- a/memgpt/agent.py+++ b/memgpt/agent.py@@ -8,8 +8,8 @@ import threadingimport openaifrom .system import get_heartbeat, get_login_event, package_function_response, package_summarize_message, get_initial_boot_messages-from .memory import CoreMemory as Memory, summarize_messages-from .openai_tools import acompletions_with_backoff as acreate+from .memory import CoreMemory as Memory, summarize_messages, a_summarize_messages+from .openai_tools import acompletions_with_backoff as acreate, completions_with_backoff as createfrom .utils import get_local_time, parse_json, united_diff, printd, count_tokensfrom .constants import (FIRST_MESSAGE_ATTEMPTS,@@ -94,6 +94,35 @@ def initialize_message_sequence(return messages+def get_ai_reply(+ model,+ message_sequence,+ functions,+ function_call="auto",+):+ try:+ response = create(+ model=model,+ messages=message_sequence,+ functions=functions,+ function_call=function_call,+ )++ # special case for 'length'+ if response.choices[0].finish_reason == "length":+ raise Exception("Finish reason was length (maximum context length)")++ # catches for soft errors+ if response.choices[0].finish_reason not in ["stop", "function_call"]:+ raise Exception(f"API call finish with bad finish reason: {response}")++ # unpack with response.choices[0].message.content+ return response++ except Exception as e:+ raise e++async def get_ai_reply_async(model,message_sequence,@@ -125,9 +154,7 @@ async def get_ai_reply_async(raise e-class AgentAsync(object):- """Core logic for a MemGPT agent"""-+class Agent(object):def __init__(self,model,@@ -189,6 +216,31 @@ class AgentAsync(object):# When the summarizer is run, set this back to False (to reset)self.agent_alerted_about_memory_pressure = False+ self.init_avail_functions()++ def init_avail_functions(self):+ """+ Allows subclasses to overwrite this dictionary with overriden methods.+ """+ self.available_functions = {+ # These functions aren't all visible to the LLM+ # To see what functions the LLM sees, check self.functions+ "send_message": self.send_ai_message,+ "edit_memory": self.edit_memory,+ "edit_memory_append": self.edit_memory_append,+ "edit_memory_replace": self.edit_memory_replace,+ "pause_heartbeats": self.pause_heartbeats,+ "message_chatgpt": self.message_chatgpt,+ "core_memory_append": self.edit_memory_append,+ "core_memory_replace": self.edit_memory_replace,+ "recall_memory_search": self.recall_memory_search,+ "recall_memory_search_date": self.recall_memory_search_date,+ "conversation_search": self.recall_memory_search,+ "conversation_search_date": self.recall_memory_search_date,+ "archival_memory_insert": self.archival_memory_insert,+ "archival_memory_search": self.archival_memory_search,+ }+@propertydef messages(self):return self._messages@@ -333,41 +385,62 @@ class AgentAsync(object):state = json.load(file)self.load_inplace(state)- async def handle_ai_response(self, response_message):+ def verify_first_message_correctness(self, response, require_send_message=True, require_monologue=False):+ """Can be used to enforce that the first message always uses send_message"""+ response_message = response.choices[0].message++ # First message should be a call to send_message with a non-empty content+ if require_send_message and not response_message.get("function_call"):+ printd(f"First message didn't include function call: {response_message}")+ return False++ function_name = response_message["function_call"]["name"]+ if require_send_message and function_name != "send_message":+ printd(f"First message function call wasn't send_message: {response_message}")+ return False++ if require_monologue and (+ not response_message.get("content") or response_message["content"] is None or response_message["content"] == ""+ ):+ printd(f"First message missing internal monologue: {response_message}")+ return False++ if response_message.get("content"):+ ### Extras+ monologue = response_message.get("content")++ def contains_special_characters(s):+ special_characters = '(){}[]"'+ return any(char in s for char in special_characters)++ if contains_special_characters(monologue):+ printd(f"First message internal monologue contained special characters: {response_message}")+ return False+ # if 'functions' in monologue or 'send_message' in monologue or 'inner thought' in monologue.lower():+ if "functions" in monologue or "send_message" in monologue:+ # Sometimes the syntax won't be correct and internal syntax will leak into message.context+ printd(f"First message internal monologue contained reserved words: {response_message}")+ return False++ return True++ def handle_ai_response(self, response_message):"""Handles parsing and function execution"""messages = [] # append these to the history when done# Step 2: check if LLM wanted to call a functionif response_message.get("function_call"):# The content if then internal monologue, not chat- await self.interface.internal_monologue(response_message.content)+ self.interface.internal_monologue(response_message.content)messages.append(response_message) # extend conversation with assistant's reply# Step 3: call the function# Note: the JSON response may not always be valid; be sure to handle errors- available_functions = {- # These functions aren't all visible to the LLM- # To see what functions the LLM sees, check self.functions- "send_message": self.send_ai_message,- "edit_memory": self.edit_memory,- "edit_memory_append": self.edit_memory_append,- "edit_memory_replace": self.edit_memory_replace,- "pause_heartbeats": self.pause_heartbeats,- "message_chatgpt": self.message_chatgpt,- "core_memory_append": self.edit_memory_append,- "core_memory_replace": self.edit_memory_replace,- "recall_memory_search": self.recall_memory_search,- "recall_memory_search_date": self.recall_memory_search_date,- "conversation_search": self.recall_memory_search,- "conversation_search_date": self.recall_memory_search_date,- "archival_memory_insert": self.archival_memory_insert,- "archival_memory_search": self.archival_memory_search,- }# Failure case 1: function name is wrongfunction_name = response_message["function_call"]["name"]try:- function_to_call = available_functions[function_name]+ function_to_call = self.available_functions[function_name]except KeyError as e:error_msg = f"No function named {function_name}"function_response = package_function_response(False, error_msg)@@ -378,7 +451,7 @@ class AgentAsync(object):"content": function_response,}) # extend conversation with function response- await self.interface.function_message(f"Error: {error_msg}")+ self.interface.function_message(f"Error: {error_msg}")return messages, None, True # force a heartbeat to allow agent to handle error# Failure case 2: function name is OK, but function args are bad JSON@@ -395,7 +468,7 @@ class AgentAsync(object):"content": function_response,}) # extend conversation with function response- await self.interface.function_message(f"Error: {error_msg}")+ self.interface.function_message(f"Error: {error_msg}")return messages, None, True # force a heartbeat to allow agent to handle error# (Still parsing function args)@@ -408,9 +481,9 @@ class AgentAsync(object):heartbeat_request = None# Failure case 3: function failed during execution- await self.interface.function_message(f"Running {function_name}({function_args})")+ self.interface.function_message(f"Running {function_name}({function_args})")try:- function_response_string = await function_to_call(**function_args)+ function_response_string = function_to_call(**function_args)function_response = package_function_response(True, function_response_string)function_failed = Falseexcept Exception as e:@@ -424,12 +497,12 @@ class AgentAsync(object):"content": function_response,}) # extend conversation with function response- await self.interface.function_message(f"Error: {error_msg}")+ self.interface.function_message(f"Error: {error_msg}")return messages, None, True # force a heartbeat to allow agent to handle error# If no failures happened along the way: ...# Step 4: send the info on the function call and function response to GPT- await self.interface.function_message(f"Success: {function_response_string}")+ self.interface.function_message(f"Success: {function_response_string}")messages.append({"role": "function",@@ -440,51 +513,343 @@ class AgentAsync(object):else:# Standard non-function reply- await self.interface.internal_monologue(response_message.content)+ self.interface.internal_monologue(response_message.content)messages.append(response_message) # extend conversation with assistant's replyheartbeat_request = Nonefunction_failed = Nonereturn messages, heartbeat_request, function_failed- def verify_first_message_correctness(self, response, require_send_message=True, require_monologue=False):- """Can be used to enforce that the first message always uses send_message"""- response_message = response.choices[0].message+ def step(self, user_message, first_message=False, first_message_retry_limit=FIRST_MESSAGE_ATTEMPTS, skip_verify=False):+ """Top-level event message handler for the MemGPT agent"""- # First message should be a call to send_message with a non-empty content- if require_send_message and not response_message.get("function_call"):- printd(f"First message didn't include function call: {response_message}")- return False+ try:+ # Step 0: add user message+ if user_message is not None:+ self.interface.user_message(user_message)+ packed_user_message = {"role": "user", "content": user_message}+ input_message_sequence = self.messages + [packed_user_message]+ else:+ input_message_sequence = self.messages- function_name = response_message["function_call"]["name"]- if require_send_message and function_name != "send_message":- printd(f"First message function call wasn't send_message: {response_message}")- return False+ if len(input_message_sequence) > 1 and input_message_sequence[-1]["role"] != "user":+ printd(f"WARNING: attempting to run ChatCompletion without user as the last message in the queue")- if require_monologue and (- not response_message.get("content") or response_message["content"] is None or response_message["content"] == ""- ):- printd(f"First message missing internal monologue: {response_message}")+ # Step 1: send the conversation and available functions to GPT+ if not skip_verify and (first_message or self.messages_total == self.messages_total_init):+ printd(f"This is the first message. Running extra verifier on AI response.")+ counter = 0+ while True:+ response = get_ai_reply(model=self.model, message_sequence=input_message_sequence, functions=self.functions)+ if self.verify_first_message_correctness(response, require_monologue=self.first_message_verify_mono):+ break++ counter += 1+ if counter > first_message_retry_limit:+ raise Exception(f"Hit first message retry limit ({first_message_retry_limit})")++ else:+ response = get_ai_reply(model=self.model, message_sequence=input_message_sequence, functions=self.functions)++ # Step 2: check if LLM wanted to call a function+ # (if yes) Step 3: call the function+ # (if yes) Step 4: send the info on the function call and function response to LLM+ response_message = response.choices[0].message+ response_message_copy = response_message.copy()+ all_response_messages, heartbeat_request, function_failed = self.handle_ai_response(response_message)++ # Add the extra metadata to the assistant response+ # (e.g. enough metadata to enable recreating the API call)+ assert "api_response" not in all_response_messages[0]+ all_response_messages[0]["api_response"] = response_message_copy+ assert "api_args" not in all_response_messages[0]+ all_response_messages[0]["api_args"] = {+ "model": self.model,+ "messages": input_message_sequence,+ "functions": self.functions,+ }++ # Step 4: extend the message history+ if user_message is not None:+ all_new_messages = [packed_user_message] + all_response_messages+ else:+ all_new_messages = all_response_messages++ # Check the memory pressure and potentially issue a memory pressure warning+ current_total_tokens = response["usage"]["total_tokens"]+ active_memory_warning = False+ if current_total_tokens > MESSAGE_SUMMARY_WARNING_TOKENS:+ printd(f"WARNING: last response total_tokens ({current_total_tokens}) > {MESSAGE_SUMMARY_WARNING_TOKENS}")+ # Only deliver the alert if we haven't already (this period)+ if not self.agent_alerted_about_memory_pressure:+ active_memory_warning = True+ self.agent_alerted_about_memory_pressure = True # it's up to the outer loop to handle this+ else:+ printd(f"last response total_tokens ({current_total_tokens}) < {MESSAGE_SUMMARY_WARNING_TOKENS}")++ self.append_to_messages(all_new_messages)+ return all_new_messages, heartbeat_request, function_failed, active_memory_warning++ except Exception as e:+ printd(f"step() failed\nuser_message = {user_message}\nerror = {e}")++ # If we got a context alert, try trimming the messages length, then try again+ if "maximum context length" in str(e):+ # A separate API call to run a summarizer+ self.summarize_messages_inplace()++ # Try step again+ return self.step(user_message, first_message=first_message)+ else:+ printd(f"step() failed with openai.InvalidRequestError, but didn't recognize the error message: '{str(e)}'")+ raise e++ def summarize_messages_inplace(self, cutoff=None):+ if cutoff is None:+ tokens_so_far = 0 # Smart cutoff -- just below the max.+ cutoff = len(self.messages) - 1+ for m in reversed(self.messages):+ tokens_so_far += count_tokens(str(m), self.model)+ if tokens_so_far >= MESSAGE_SUMMARY_WARNING_TOKENS * 0.2:+ break+ cutoff -= 1+ cutoff = min(len(self.messages) - 3, cutoff) # Always keep the last two messages too++ # Try to make an assistant message come after the cutoff+ try:+ printd(f"Selected cutoff {cutoff} was a 'user', shifting one...")+ if self.messages[cutoff]["role"] == "user":+ new_cutoff = cutoff + 1+ if self.messages[new_cutoff]["role"] == "user":+ printd(f"Shifted cutoff {new_cutoff} is still a 'user', ignoring...")+ cutoff = new_cutoff+ except IndexError:+ pass++ message_sequence_to_summarize = self.messages[1:cutoff] # do NOT get rid of the system message+ printd(f"Attempting to summarize {len(message_sequence_to_summarize)} messages [1:{cutoff}] of {len(self.messages)}")++ summary = summarize_messages(self.model, message_sequence_to_summarize)+ printd(f"Got summary: {summary}")++ # Metadata that's useful for the agent to see+ all_time_message_count = self.messages_total+ remaining_message_count = len(self.messages[cutoff:])+ hidden_message_count = all_time_message_count - remaining_message_count+ summary_message_count = len(message_sequence_to_summarize)+ summary_message = package_summarize_message(summary, summary_message_count, hidden_message_count, all_time_message_count)+ printd(f"Packaged into message: {summary_message}")++ prior_len = len(self.messages)+ self.trim_messages(cutoff)+ packed_summary_message = {"role": "user", "content": summary_message}+ self.prepend_to_messages([packed_summary_message])++ # reset alert+ self.agent_alerted_about_memory_pressure = False++ printd(f"Ran summarizer, messages length {prior_len} -> {len(self.messages)}")++ def send_ai_message(self, message):+ """AI wanted to send a message"""+ self.interface.assistant_message(message)+ return None++ def edit_memory(self, name, content):+ """Edit memory.name <= content"""+ new_len = self.memory.edit(name, content)+ self.rebuild_memory()+ return None++ def edit_memory_append(self, name, content):+ new_len = self.memory.edit_append(name, content)+ self.rebuild_memory()+ return None++ def edit_memory_replace(self, name, old_content, new_content):+ new_len = self.memory.edit_replace(name, old_content, new_content)+ self.rebuild_memory()+ return None++ def recall_memory_search(self, query, count=5, page=0):+ results, total = self.persistence_manager.recall_memory.text_search(query, count=count, start=page * count)+ num_pages = math.ceil(total / count) - 1 # 0 index+ if len(results) == 0:+ results_str = f"No results found."+ else:+ results_pref = f"Showing {len(results)} of {total} results (page {page}/{num_pages}):"+ results_formatted = [f"timestamp: {d['timestamp']}, {d['message']['role']} - {d['message']['content']}" for d in results]+ results_str = f"{results_pref} {json.dumps(results_formatted)}"+ return results_str++ def recall_memory_search_date(self, start_date, end_date, count=5, page=0):+ results, total = self.persistence_manager.recall_memory.date_search(start_date, end_date, count=count, start=page * count)+ num_pages = math.ceil(total / count) - 1 # 0 index+ if len(results) == 0:+ results_str = f"No results found."+ else:+ results_pref = f"Showing {len(results)} of {total} results (page {page}/{num_pages}):"+ results_formatted = [f"timestamp: {d['timestamp']}, {d['message']['role']} - {d['message']['content']}" for d in results]+ results_str = f"{results_pref} {json.dumps(results_formatted)}"+ return results_str++ def archival_memory_insert(self, content, embedding=None):+ self.persistence_manager.archival_memory.insert(content, embedding=None)+ return None++ def archival_memory_search(self, query, count=5, page=0):+ results, total = self.persistence_manager.archival_memory.search(query, count=count, start=page * count)+ num_pages = math.ceil(total / count) - 1 # 0 index+ if len(results) == 0:+ results_str = f"No results found."+ else:+ results_pref = f"Showing {len(results)} of {total} results (page {page}/{num_pages}):"+ results_formatted = [f"timestamp: {d['timestamp']}, memory: {d['content']}" for d in results]+ results_str = f"{results_pref} {json.dumps(results_formatted)}"+ return results_str++ def message_chatgpt(self, message):+ """Base call to GPT API w/ functions"""++ message_sequence = [+ {"role": "system", "content": MESSAGE_CHATGPT_FUNCTION_SYSTEM_MESSAGE},+ {"role": "user", "content": str(message)},+ ]+ response = create(+ model=MESSAGE_CHATGPT_FUNCTION_MODEL,+ messages=message_sequence,+ # functions=functions,+ # function_call=function_call,+ )++ reply = response.choices[0].message.content+ return reply++ def pause_heartbeats(self, minutes, max_pause=MAX_PAUSE_HEARTBEATS):+ """Pause timed heartbeats for N minutes"""+ minutes = min(max_pause, minutes)++ # Record the current time+ self.pause_heartbeats_start = datetime.datetime.now()+ # And record how long the pause should go for+ self.pause_heartbeats_minutes = int(minutes)++ return f"Pausing timed heartbeats for {minutes} min"++ def heartbeat_is_paused(self):+ """Check if there's a requested pause on timed heartbeats"""++ # Check if the pause has been initiated+ if self.pause_heartbeats_start is None:return False- if response_message.get("content"):- ### Extras- monologue = response_message.get("content")+ # Check if it's been more than pause_heartbeats_minutes since pause_heartbeats_start+ elapsed_time = datetime.datetime.now() - self.pause_heartbeats_start+ return elapsed_time.total_seconds() < self.pause_heartbeats_minutes * 60- def contains_special_characters(s):- special_characters = '(){}[]"'- return any(char in s for char in special_characters)- if contains_special_characters(monologue):- printd(f"First message internal monologue contained special characters: {response_message}")- return False- # if 'functions' in monologue or 'send_message' in monologue or 'inner thought' in monologue.lower():- if "functions" in monologue or "send_message" in monologue:- # Sometimes the syntax won't be correct and internal syntax will leak into message.context- printd(f"First message internal monologue contained reserved words: {response_message}")- return False+class AgentAsync(Agent):+ """Core logic for an async MemGPT agent"""- return True+ def __init__(self, **kwargs):+ super().__init__(**kwargs)+ self.init_avail_functions()++ async def handle_ai_response(self, response_message):+ """Handles parsing and function execution"""+ messages = [] # append these to the history when done++ # Step 2: check if LLM wanted to call a function+ if response_message.get("function_call"):+ # The content if then internal monologue, not chat+ await self.interface.internal_monologue(response_message.content)+ messages.append(response_message) # extend conversation with assistant's reply++ # Step 3: call the function+ # Note: the JSON response may not always be valid; be sure to handle errors++ # Failure case 1: function name is wrong+ function_name = response_message["function_call"]["name"]+ try:+ function_to_call = self.available_functions[function_name]+ except KeyError as e:+ error_msg = f"No function named {function_name}"+ function_response = package_function_response(False, error_msg)+ messages.append(+ {+ "role": "function",+ "name": function_name,+ "content": function_response,+ }+ ) # extend conversation with function response+ await self.interface.function_message(f"Error: {error_msg}")+ return messages, None, True # force a heartbeat to allow agent to handle error++ # Failure case 2: function name is OK, but function args are bad JSON+ try:+ raw_function_args = response_message["function_call"]["arguments"]+ function_args = parse_json(raw_function_args)+ except Exception as e:+ error_msg = f"Error parsing JSON for function '{function_name}' arguments: {raw_function_args}"+ function_response = package_function_response(False, error_msg)+ messages.append(+ {+ "role": "function",+ "name": function_name,+ "content": function_response,+ }+ ) # extend conversation with function response+ await self.interface.function_message(f"Error: {error_msg}")+ return messages, None, True # force a heartbeat to allow agent to handle error++ # (Still parsing function args)+ # Handle requests for immediate heartbeat+ heartbeat_request = function_args.pop("request_heartbeat", None)+ if not (isinstance(heartbeat_request, bool) or heartbeat_request is None):+ printd(+ f"Warning: 'request_heartbeat' arg parsed was not a bool or None, type={type(heartbeat_request)}, value={heartbeat_request}"+ )+ heartbeat_request = None++ # Failure case 3: function failed during execution+ await self.interface.function_message(f"Running {function_name}({function_args})")+ try:+ function_response_string = await function_to_call(**function_args)+ function_response = package_function_response(True, function_response_string)+ function_failed = False+ except Exception as e:+ error_msg = f"Error calling function {function_name} with args {function_args}: {str(e)}"+ printd(error_msg)+ function_response = package_function_response(False, error_msg)+ messages.append(+ {+ "role": "function",+ "name": function_name,+ "content": function_response,+ }+ ) # extend conversation with function response+ await self.interface.function_message(f"Error: {error_msg}")+ return messages, None, True # force a heartbeat to allow agent to handle error++ # If no failures happened along the way: ...+ # Step 4: send the info on the function call and function response to GPT+ await self.interface.function_message(f"Success: {function_response_string}")+ messages.append(+ {+ "role": "function",+ "name": function_name,+ "content": function_response,+ }+ ) # extend conversation with function response++ else:+ # Standard non-function reply+ await self.interface.internal_monologue(response_message.content)+ messages.append(response_message) # extend conversation with assistant's reply+ heartbeat_request = None+ function_failed = None++ return messages, heartbeat_request, function_failedasync def step(self, user_message, first_message=False, first_message_retry_limit=FIRST_MESSAGE_ATTEMPTS, skip_verify=False):"""Top-level event message handler for the MemGPT agent"""@@ -647,24 +1012,8 @@ class AgentAsync(object):await self.interface.assistant_message(message)return None- async def edit_memory(self, name, content):- """Edit memory.name <= content"""- new_len = self.memory.edit(name, content)- self.rebuild_memory()- return None-- async def edit_memory_append(self, name, content):- new_len = self.memory.edit_append(name, content)- self.rebuild_memory()- return None-- async def edit_memory_replace(self, name, old_content, new_content):- new_len = self.memory.edit_replace(name, old_content, new_content)- self.rebuild_memory()- return None-async def recall_memory_search(self, query, count=5, page=0):- results, total = await self.persistence_manager.recall_memory.text_search(query, count=count, start=page * count)+ results, total = await self.persistence_manager.recall_memory.a_text_search(query, count=count, start=page * count)num_pages = math.ceil(total / count) - 1 # 0 indexif len(results) == 0:results_str = f"No results found."@@ -675,7 +1024,7 @@ class AgentAsync(object):return results_strasync def recall_memory_search_date(self, start_date, end_date, count=5, page=0):- results, total = await self.persistence_manager.recall_memory.date_search(start_date, end_date, count=count, start=page * count)+ results, total = await self.persistence_manager.recall_memory.a_date_search(start_date, end_date, count=count, start=page * count)num_pages = math.ceil(total / count) - 1 # 0 indexif len(results) == 0:results_str = f"No results found."@@ -686,11 +1035,11 @@ class AgentAsync(object):return results_strasync def archival_memory_insert(self, content, embedding=None):- await self.persistence_manager.archival_memory.insert(content, embedding=None)+ await self.persistence_manager.archival_memory.a_insert(content, embedding=None)return Noneasync def archival_memory_search(self, query, count=5, page=0):- results, total = await self.persistence_manager.archival_memory.search(query, count=count, start=page * count)+ results, total = await self.persistence_manager.archival_memory.a_search(query, count=count, start=page * count)num_pages = math.ceil(total / count) - 1 # 0 indexif len(results) == 0:results_str = f"No results found."@@ -700,28 +1049,6 @@ class AgentAsync(object):results_str = f"{results_pref} {json.dumps(results_formatted)}"return results_str- async def pause_heartbeats(self, minutes, max_pause=MAX_PAUSE_HEARTBEATS):- """Pause timed heartbeats for N minutes"""- minutes = min(max_pause, minutes)-- # Record the current time- self.pause_heartbeats_start = datetime.datetime.now()- # And record how long the pause should go for- self.pause_heartbeats_minutes = int(minutes)-- return f"Pausing timed heartbeats for {minutes} min"-- def heartbeat_is_paused(self):- """Check if there's a requested pause on timed heartbeats"""-- # Check if the pause has been initiated- if self.pause_heartbeats_start is None:- return False-- # Check if it's been more than pause_heartbeats_minutes since pause_heartbeats_start- elapsed_time = datetime.datetime.now() - self.pause_heartbeats_start- return elapsed_time.total_seconds() < self.pause_heartbeats_minutes * 60-async def message_chatgpt(self, message):"""Base call to GPT API w/ functions"""diff --git a/memgpt/memory.py b/memgpt/memory.pyindex 157255b76..8b3130c36 100644--- a/memgpt/memory.py+++ b/memgpt/memory.py@@ -9,7 +9,12 @@ from typing import Optional, List, Tuplefrom .constants import MESSAGE_SUMMARY_WARNING_TOKENS, MEMGPT_DIRfrom .utils import cosine_similarity, get_local_time, printd, count_tokensfrom .prompts.gpt_summarize import SYSTEM as SUMMARY_PROMPT_SYSTEM-from .openai_tools import acompletions_with_backoff as acreate, async_get_embedding_with_backoff+from .openai_tools import (+ acompletions_with_backoff as acreate,+ async_get_embedding_with_backoff,+ get_embedding_with_backoff,+ completions_with_backoff as create,+)from llama_index import (VectorStoreIndex,@@ -107,7 +112,35 @@ class CoreMemory(object):raise KeyError-async def summarize_messages(+def summarize_messages(+ model,+ message_sequence_to_summarize,+):+ """Summarize a message sequence using GPT"""++ summary_prompt = SUMMARY_PROMPT_SYSTEM+ summary_input = str(message_sequence_to_summarize)+ summary_input_tkns = count_tokens(summary_input, model)+ if summary_input_tkns > MESSAGE_SUMMARY_WARNING_TOKENS:+ trunc_ratio = (MESSAGE_SUMMARY_WARNING_TOKENS / summary_input_tkns) * 0.8 # For good measure...+ cutoff = int(len(message_sequence_to_summarize) * trunc_ratio)+ summary_input = str([summarize_messages(model, message_sequence_to_summarize[:cutoff])] + message_sequence_to_summarize[cutoff:])+ message_sequence = [+ {"role": "system", "content": summary_prompt},+ {"role": "user", "content": summary_input},+ ]++ response = create(+ model=model,+ messages=message_sequence,+ )++ printd(f"summarize_messages gpt reply: {response.choices[0]}")+ reply = response.choices[0].message.content+ return reply+++async def a_summarize_messages(model,message_sequence_to_summarize,):@@ -188,7 +221,7 @@ class DummyArchivalMemory(ArchivalMemory):memory_str = "\n".join([d["content"] for d in self._archive])return f"\n### ARCHIVAL MEMORY ###" + f"\n{memory_str}"- async def insert(self, memory_string, embedding=None):+ def insert(self, memory_string, embedding=None):if embedding is not None:raise ValueError("Basic text-based archival memory does not support embeddings")self._archive.append(@@ -199,7 +232,10 @@ class DummyArchivalMemory(ArchivalMemory):})- async def search(self, query_string, count=None, start=None):+ async def a_insert(self, memory_string, embedding=None):+ return self.insert(memory_string, embedding)++ def search(self, query_string, count=None, start=None):"""Simple text-based search"""# in the dummy version, run an (inefficient) case-insensitive match search# printd(f"query_string: {query_string}")@@ -219,6 +255,9 @@ class DummyArchivalMemory(ArchivalMemory):else:return matches, len(matches)+ async def a_search(self, query_string, count=None, start=None):+ return self.search(query_string, count=None, start=None)+class DummyArchivalMemoryWithEmbeddings(DummyArchivalMemory):"""Same as dummy in-memory archival memory, but with bare-bones embedding support"""@@ -230,10 +269,8 @@ class DummyArchivalMemoryWithEmbeddings(DummyArchivalMemory):def __len__(self):return len(self._archive)- async def insert(self, memory_string, embedding=None):+ def _insert(self, memory_string, embedding):# Get the embedding- if embedding is None:- embedding = await async_get_embedding_with_backoff(memory_string, model=self.embedding_model)embedding_meta = {"model": self.embedding_model}printd(f"Got an embedding, type {type(embedding)}, len {len(embedding)}")@@ -246,13 +283,22 @@ class DummyArchivalMemoryWithEmbeddings(DummyArchivalMemory):})- async def search(self, query_string, count=None, start=None):+ def insert(self, memory_string, embedding=None):+ if embedding is None:+ embedding = get_embedding_with_backoff(memory_string, model=self.embedding_model)+ return self._insert(memory_string, embedding)++ async def a_insert(self, memory_string, embedding=None):+ if embedding is None:+ embedding = await async_get_embedding_with_backoff(memory_string, model=self.embedding_model)+ return self._insert(memory_string, embedding)++ def _search(self, query_embedding, query_string, count, start):"""Simple embedding-based search (inefficient, no caching)"""# see: https://github.com/openai/openai-cookbook/blob/main/examples/Semantic_text_search_using_embeddings.ipynb# query_embedding = get_embedding(query_string, model=self.embedding_model)# our wrapped version supports backoff/rate-limits- query_embedding = await async_get_embedding_with_backoff(query_string, model=self.embedding_model)similarity_scores = [cosine_similarity(memory["embedding"], query_embedding) for memory in self._archive]# Sort the archive based on similarity scores@@ -278,6 +324,14 @@ class DummyArchivalMemoryWithEmbeddings(DummyArchivalMemory):else:return matches, len(matches)+ def search(self, query_string, count=None, start=None):+ query_embedding = get_embedding_with_backoff(query_string, model=self.embedding_model)+ return self._search(self, query_embedding, query_string, count, start)++ async def a_search(self, query_string, count=None, start=None):+ query_embedding = await async_get_embedding_with_backoff(query_string, model=self.embedding_model)+ return await self._search(self, query_embedding, query_string, count, start)+class DummyArchivalMemoryWithFaiss(DummyArchivalMemory):"""Dummy in-memory version of an archival memory database, using a FAISS@@ -305,10 +359,7 @@ class DummyArchivalMemoryWithFaiss(DummyArchivalMemory):def __len__(self):return len(self._archive)- async def insert(self, memory_string, embedding=None):- if embedding is None:- # Get the embedding- embedding = await async_get_embedding_with_backoff(memory_string, model=self.embedding_model)+ def _insert(self, memory_string, embedding):print(f"Got an embedding, type {type(embedding)}, len {len(embedding)}")self._archive.append(@@ -321,17 +372,27 @@ class DummyArchivalMemoryWithFaiss(DummyArchivalMemory):embedding = np.array([embedding]).astype("float32")self.index.add(embedding)- async def search(self, query_string, count=None, start=None):+ def insert(self, memory_string, embedding=None):+ if embedding is None:+ # Get the embedding+ embedding = get_embedding_with_backoff(memory_string, model=self.embedding_model)+ return self._insert(memory_string, embedding)++ async def a_insert(self, memory_string, embedding=None):+ if embedding is None:+ # Get the embedding+ embedding = async_get_embedding_with_backoff(memory_string, model=self.embedding_model)+ return await self._insert(memory_string, embedding)++ def _search(self, query_embedding, query_string, count=None, start=None):"""Simple embedding-based search (inefficient, no caching)"""# see: https://github.com/openai/openai-cookbook/blob/main/examples/Semantic_text_search_using_embeddings.ipynb# query_embedding = get_embedding(query_string, model=self.embedding_model)# our wrapped version supports backoff/rate-limitsif query_string in self.embeddings_dict:- query_embedding = self.embeddings_dict[query_string]search_result = self.search_results[query_string]else:- query_embedding = await async_get_embedding_with_backoff(query_string, model=self.embedding_model)_, indices = self.index.search(np.array([np.array(query_embedding, dtype=np.float32)]), self.k)search_result = [self._archive[idx] if idx < len(self._archive) else "" for idx in indices[0]]self.embeddings_dict[query_string] = query_embedding@@ -361,16 +422,38 @@ class DummyArchivalMemoryWithFaiss(DummyArchivalMemory):else:return matches, len(matches)+ def search(self, query_string, count=None, start=None):+ if query_string in self.embeddings_dict:+ query_embedding = self.embeddings_dict[query_string]+ else:+ query_embedding = get_embedding_with_backoff(query_string, model=self.embedding_model)+ return self._search(query_embedding, query_string, count, start)++ async def a_search(self, query_string, count=None, start=None):+ if query_string in self.embeddings_dict:+ query_embedding = self.embeddings_dict[query_string]+ else:+ query_embedding = await async_get_embedding_with_backoff(query_string, model=self.embedding_model)+ return self._search(query_embedding, query_string, count, start)+class RecallMemory(ABC):@abstractmethoddef text_search(self, query_string, count=None, start=None):pass+ @abstractmethod+ async def a_text_search(self, query_string, count=None, start=None):+ pass+@abstractmethoddef date_search(self, query_string, count=None, start=None):pass+ @abstractmethod+ async def a_date_search(self, query_string, count=None, start=None):+ pass+@abstractmethoddef __repr__(self) -> str:pass@@ -425,7 +508,7 @@ class DummyRecallMemory(RecallMemory):async def insert(self, message):raise NotImplementedError("This should be handled by the PersistenceManager, recall memory is just a search layer on top")- async def text_search(self, query_string, count=None, start=None):+ def text_search(self, query_string, count=None, start=None):# in the dummy version, run an (inefficient) case-insensitive match searchmessage_pool = [d for d in self._message_logs if d["message"]["role"] not in ["system", "function"]]@@ -447,6 +530,9 @@ class DummyRecallMemory(RecallMemory):else:return matches, len(matches)+ async def a_text_search(self, query_string, count=None, start=None):+ return self.text_search(query_string, count, start)+def _validate_date_format(self, date_str):"""Validate the given date string in the format 'YYYY-MM-DD'."""try:@@ -461,7 +547,7 @@ class DummyRecallMemory(RecallMemory):match = re.match(r"(\d{4}-\d{2}-\d{2})", timestamp)return match.group(1) if match else None- async def date_search(self, start_date, end_date, count=None, start=None):+ def date_search(self, start_date, end_date, count=None, start=None):message_pool = [d for d in self._message_logs if d["message"]["role"] not in ["system", "function"]]# First, validate the start_date and end_date format@@ -489,6 +575,9 @@ class DummyRecallMemory(RecallMemory):else:return matches, len(matches)+ def a_date_search(self, start_date, end_date, count=None, start=None):+ return self.date_search(start_date, end_date, count, start)+class DummyRecallMemoryWithEmbeddings(DummyRecallMemory):"""Lazily manage embeddings by keeping a string->embed dict"""@@ -499,7 +588,7 @@ class DummyRecallMemoryWithEmbeddings(DummyRecallMemory):self.embedding_model = "text-embedding-ada-002"self.only_use_preloaded_embeddings = False- async def text_search(self, query_string, count=None, start=None):+ def _text_search(self, embedding_getter_func, query_string, count, start):# in the dummy version, run an (inefficient) case-insensitive match searchmessage_pool = [d for d in self._message_logs if d["message"]["role"] not in ["system", "function"]]@@ -514,11 +603,11 @@ class DummyRecallMemoryWithEmbeddings(DummyRecallMemory):message_pool_filtered.append(d)elif message_str not in self.embeddings:printd(f"recall_memory.text_search -- '{message_str}' was not in embedding dict, computing now")- self.embeddings[message_str] = await async_get_embedding_with_backoff(message_str, model=self.embedding_model)+ self.embeddings[message_str] = embedding_getter_func(message_str, model=self.embedding_model)message_pool_filtered.append(d)# our wrapped version supports backoff/rate-limits- query_embedding = await async_get_embedding_with_backoff(query_string, model=self.embedding_model)+ query_embedding = embedding_getter_func(query_string, model=self.embedding_model)similarity_scores = [cosine_similarity(self.embeddings[d["message"]["content"]], query_embedding) for d in message_pool_filtered]# Sort the archive based on similarity scores@@ -544,6 +633,12 @@ class DummyRecallMemoryWithEmbeddings(DummyRecallMemory):else:return matches, len(matches)+ def text_search(self, query_string, count=None, start=None):+ return self._text_search(get_embedding_with_backoff, query_string, count, start)++ async def a_text_search(self, query_string, count=None, start=None):+ return await self._text_search(async_get_embedding_with_backoff, query_string, count, start)+class LocalArchivalMemory(ArchivalMemory):"""Archival memory built on top of Llama Index"""@@ -571,10 +666,13 @@ class LocalArchivalMemory(ArchivalMemory):# TODO: have some mechanism for cleanup otherwise will lead to OOMself.cache = {}- async def insert(self, memory_string):+ def insert(self, memory_string):self.index.insert(memory_string)- async def search(self, query_string, count=None, start=None):+ async def a_insert(self, memory_string):+ return self.insert(memory_string)++ def search(self, query_string, count=None, start=None):start = start if start else 0count = count if count else self.top_kcount = min(count + start, self.top_k)@@ -587,6 +685,9 @@ class LocalArchivalMemory(ArchivalMemory):# from pprint import pprint# pprint(results)return results, len(results)++ async def a_search(self, query_string, count=None, start=None):+ return self.search(query_string, count, start)def __repr__(self) -> str:print(self.index.ref_doc_info)diff --git a/memgpt/openai_tools.py b/memgpt/openai_tools.pyindex 6b97b06a1..23cd9d055 100644--- a/memgpt/openai_tools.py+++ b/memgpt/openai_tools.py@@ -144,6 +144,25 @@ async def async_get_embedding_with_backoff(text, model="text-embedding-ada-002")return embedding+@retry_with_exponential_backoff+def create_embedding_with_backoff(**kwargs):+ if using_azure():+ azure_openai_deployment = os.getenv("AZURE_OPENAI_EMBEDDINGS_DEPLOYMENT")+ if azure_openai_deployment is not None:+ kwargs["deployment_id"] = azure_openai_deployment+ else:+ kwargs["engine"] = kwargs["model"]+ kwargs.pop("model")+ return openai.Embedding.create(**kwargs)+++def get_embedding_with_backoff(text, model="text-embedding-ada-002"):+ text = text.replace("\n", " ")+ response = create_embedding_with_backoff(input=[text], model=model)+ embedding = response["data"][0]["embedding"]+ return embedding++MODEL_TO_AZURE_ENGINE = {"gpt-4": "gpt-4","gpt-4-32k": "gpt-4-32k",