Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
Patch summarize when running with local llms (#213)
Charles Packerfde0087a19a8
diff --git a/memgpt/agent.py b/memgpt/agent.pyindex 3122bb5ed..aee77c8ba 100644--- a/memgpt/agent.py+++ b/memgpt/agent.py@@ -23,9 +23,12 @@ from .constants import (MESSAGE_CHATGPT_FUNCTION_MODEL,MESSAGE_CHATGPT_FUNCTION_SYSTEM_MESSAGE,MESSAGE_SUMMARY_WARNING_TOKENS,+ MESSAGE_SUMMARY_TRUNC_TOKEN_FRAC,+ MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST,CORE_MEMORY_HUMAN_CHAR_LIMIT,CORE_MEMORY_PERSONA_CHAR_LIMIT,)+from .errors import LLMErrordef initialize_memory(ai_notes, human_notes):@@ -680,16 +683,43 @@ class Agent(object):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+ def summarize_messages_inplace(self, cutoff=None, preserve_last_N_messages=True):+ assert self.messages[0]["role"] == "system", f"self.messages[0] should be system (instead got {self.messages[0]})"++ # Start at index 1 (past the system message),+ # and collect messages for summarization until we reach the desired truncation token fraction (eg 50%)+ # Do not allow truncation of the last N messages, since these are needed for in-context examples of function calling+ token_counts = [count_tokens(str(msg)) for msg in self.messages]+ message_buffer_token_count = sum(token_counts[1:]) # no system message+ desired_token_count_to_summarize = int(message_buffer_token_count * MESSAGE_SUMMARY_TRUNC_TOKEN_FRAC)+ candidate_messages_to_summarize = self.messages[1:]+ token_counts = token_counts[1:]+ if preserve_last_N_messages:+ candidate_messages_to_summarize = candidate_messages_to_summarize[:-MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST]+ token_counts = token_counts[:-MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST]+ printd(f"MESSAGE_SUMMARY_TRUNC_TOKEN_FRAC={MESSAGE_SUMMARY_TRUNC_TOKEN_FRAC}")+ printd(f"MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST={MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST}")+ printd(f"token_counts={token_counts}")+ printd(f"message_buffer_token_count={message_buffer_token_count}")+ printd(f"desired_token_count_to_summarize={desired_token_count_to_summarize}")+ printd(f"len(candidate_messages_to_summarize)={len(candidate_messages_to_summarize)}")++ # If at this point there's nothing to summarize, throw an error+ if len(candidate_messages_to_summarize) == 0:+ raise LLMError(+ f"Summarize error: tried to run summarize, but couldn't find enough messages to compress [len={len(self.messages)}, preserve_N={MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST}]"+ )++ # Walk down the message buffer (front-to-back) until we hit the target token count+ tokens_so_far = 0+ cutoff = 0+ for i, msg in enumerate(candidate_messages_to_summarize):+ cutoff = i+ tokens_so_far += token_counts[i]+ if tokens_so_far > desired_token_count_to_summarize:+ break+ # Account for system message+ cutoff += 1# Try to make an assistant message come after the cutofftry:@@ -1083,16 +1113,43 @@ class AgentAsync(Agent):print(e)raise e- async 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+ async def summarize_messages_inplace(self, cutoff=None, preserve_last_N_messages=True):+ assert self.messages[0]["role"] == "system", f"self.messages[0] should be system (instead got {self.messages[0]})"++ # Start at index 1 (past the system message),+ # and collect messages for summarization until we reach the desired truncation token fraction (eg 50%)+ # Do not allow truncation of the last N messages, since these are needed for in-context examples of function calling+ token_counts = [count_tokens(str(msg)) for msg in self.messages]+ message_buffer_token_count = sum(token_counts[1:]) # no system message+ token_counts = token_counts[1:]+ desired_token_count_to_summarize = int(message_buffer_token_count * MESSAGE_SUMMARY_TRUNC_TOKEN_FRAC)+ candidate_messages_to_summarize = self.messages[1:]+ if preserve_last_N_messages:+ candidate_messages_to_summarize = candidate_messages_to_summarize[:-MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST]+ token_counts = token_counts[:-MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST]+ printd(f"MESSAGE_SUMMARY_TRUNC_TOKEN_FRAC={MESSAGE_SUMMARY_TRUNC_TOKEN_FRAC}")+ printd(f"MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST={MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST}")+ printd(f"token_counts={token_counts}")+ printd(f"message_buffer_token_count={message_buffer_token_count}")+ printd(f"desired_token_count_to_summarize={desired_token_count_to_summarize}")+ printd(f"len(candidate_messages_to_summarize)={len(candidate_messages_to_summarize)}")++ # If at this point there's nothing to summarize, throw an error+ if len(candidate_messages_to_summarize) == 0:+ raise LLMError(+ f"Summarize error: tried to run summarize, but couldn't find enough messages to compress [len={len(self.messages)}, preserve_N={MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST}]"+ )++ # Walk down the message buffer (front-to-back) until we hit the target token count+ tokens_so_far = 0+ cutoff = 0+ for i, msg in enumerate(candidate_messages_to_summarize):+ cutoff = i+ tokens_so_far += token_counts[i]+ if tokens_so_far > desired_token_count_to_summarize:+ break+ # Account for system message+ cutoff += 1# Try to make an assistant message come after the cutofftry:@@ -1106,8 +1163,13 @@ class AgentAsync(Agent):passmessage_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)}")+ if len(message_sequence_to_summarize) == 0:+ printd(f"message_sequence_to_summarize is len 0, skipping summarize")+ raise LLMError(+ f"Summarize error: tried to run summarize, but couldn't find enough messages to compress [len={len(self.messages)}, cutoff={cutoff}]"+ )+ printd(f"Attempting to summarize {len(message_sequence_to_summarize)} messages [1:{cutoff}] of {len(self.messages)}")summary = await a_summarize_messages(self.model, message_sequence_to_summarize)printd(f"Got summary: {summary}")diff --git a/memgpt/constants.py b/memgpt/constants.pyindex aae904c4a..1326760e3 100644--- a/memgpt/constants.py+++ b/memgpt/constants.py@@ -16,8 +16,18 @@ STARTUP_QUOTES = [INITIAL_BOOT_MESSAGE_SEND_MESSAGE_FIRST_MSG = STARTUP_QUOTES[2]# Constants to do with summarization / conversation length window-MESSAGE_SUMMARY_WARNING_TOKENS = 7000 # the number of tokens consumed in a call before a system warning goes to the agent+# The max amount of tokens supported by the underlying model (eg 8k for gpt-4 and Mistral 7B)+LLM_MAX_TOKENS = 8000 # change this depending on your model+# The amount of tokens before a sytem warning about upcoming truncation is sent to MemGPT+MESSAGE_SUMMARY_WARNING_TOKENS = int(0.75 * LLM_MAX_TOKENS)+# The error message that MemGPT will receiveMESSAGE_SUMMARY_WARNING_STR = f"Warning: the conversation history will soon reach its maximum length and be trimmed. Make sure to save any important information from the conversation to your memory before it is removed."+# The fraction of tokens we truncate down to+MESSAGE_SUMMARY_TRUNC_TOKEN_FRAC = 0.75++# Even when summarizing, we want to keep a handful of recent messages+# These serve as in-context examples of how to use functions / what user messages look like+MESSAGE_SUMMARY_TRUNC_KEEP_N_LAST = 3# Default memory limitsCORE_MEMORY_PERSONA_CHAR_LIMIT = 2000diff --git a/memgpt/errors.py b/memgpt/errors.pynew file mode 100644index 000000000..aa1f57fcb--- /dev/null+++ b/memgpt/errors.py@@ -0,0 +1,28 @@+class LLMError(Exception):+ """Base class for all LLM-related errors."""++ pass+++class LLMJSONParsingError(LLMError):+ """Exception raised for errors in the JSON parsing process."""++ def __init__(self, message="Error parsing JSON generated by LLM"):+ self.message = message+ super().__init__(self.message)+++class LocalLLMError(LLMError):+ """Generic catch-all error for local LLM problems"""++ def __init__(self, message="Encountered an error while running local LLM"):+ self.message = message+ super().__init__(self.message)+++class LocalLLMConnectionError(LLMError):+ """Error for when local LLM cannot be reached with provided IP/port"""++ def __init__(self, message="Could not connect to local LLM"):+ self.message = message+ super().__init__(self.message)diff --git a/memgpt/local_llm/chat_completion_proxy.py b/memgpt/local_llm/chat_completion_proxy.pyindex 4c7216f43..f533a3387 100644--- a/memgpt/local_llm/chat_completion_proxy.py+++ b/memgpt/local_llm/chat_completion_proxy.py@@ -6,21 +6,26 @@ import jsonfrom .webui.api import get_webui_completionfrom .lmstudio.api import get_lmstudio_completion-from .llm_chat_completion_wrappers import airoboros, dolphin, zephyr+from .llm_chat_completion_wrappers import airoboros, dolphin, zephyr, simple_summary_wrapperfrom .utils import DotDict+from ..prompts.gpt_summarize import SYSTEM as SUMMARIZE_SYSTEM_MESSAGE+from ..errors import LocalLLMConnectionError, LocalLLMErrorHOST = os.getenv("OPENAI_API_BASE")HOST_TYPE = os.getenv("BACKEND_TYPE") # default None == ChatCompletionDEBUG = FalseDEFAULT_WRAPPER = airoboros.Airoboros21InnerMonologueWrapper()+has_shown_warning = Falsedef get_chat_completion(model, # no model, since the model is fixed to whatever you set in your own backendmessages,- functions,+ functions=None,function_call="auto",):+ global has_shown_warning+if HOST is None:raise ValueError(f"The OPENAI_API_BASE environment variable is not defined. Please set it in your environment.")if HOST_TYPE is None:@@ -29,7 +34,10 @@ def get_chat_completion(if function_call != "auto":raise ValueError(f"function_call == {function_call} not supported (auto only)")- if model == "airoboros-l2-70b-2.1":+ if messages[0]["role"] == "system" and messages[0]["content"].strip() == SUMMARIZE_SYSTEM_MESSAGE.strip():+ # Special case for if the call we're making is coming from the summarizer+ llm_wrapper = simple_summary_wrapper.SimpleSummaryWrapper()+ elif model == "airoboros-l2-70b-2.1":llm_wrapper = airoboros.Airoboros21InnerMonologueWrapper()elif model == "dolphin-2.1-mistral-7b":llm_wrapper = dolphin.Dolphin21MistralWrapper()@@ -37,13 +45,23 @@ def get_chat_completion(llm_wrapper = zephyr.ZephyrMistralInnerMonologueWrapper()else:# Warn the user that we're using the fallback- print(f"Warning: no wrapper specified for local LLM, using the default wrapper")+ if not has_shown_warning:+ print(+ f"Warning: no wrapper specified for local LLM, using the default wrapper (you can remove this warning by specifying the wrapper with --model)"+ )+ has_shown_warning = Truellm_wrapper = DEFAULT_WRAPPER# First step: turn the message sequence into a prompt that the model expects- prompt = llm_wrapper.chat_completion_to_prompt(messages, functions)- if DEBUG:- print(prompt)++ try:+ prompt = llm_wrapper.chat_completion_to_prompt(messages, functions)+ if DEBUG:+ print(prompt)+ except Exception as e:+ raise LocalLLMError(+ f"Failed to convert ChatCompletion messages into prompt string with wrapper {str(llm_wrapper)} - error: {str(e)}"+ )try:if HOST_TYPE == "webui":@@ -54,14 +72,17 @@ def get_chat_completion(print(f"Warning: BACKEND_TYPE was not set, defaulting to webui")result = get_webui_completion(prompt)except requests.exceptions.ConnectionError as e:- raise ValueError(f"Was unable to connect to host {HOST}")+ raise LocalLLMConnectionError(f"Unable to connect to host {HOST}")if result is None or result == "":- raise Exception(f"Got back an empty response string from {HOST}")+ raise LocalLLMError(f"Got back an empty response string from {HOST}")- chat_completion_result = llm_wrapper.output_to_chat_completion_response(result)- if DEBUG:- print(json.dumps(chat_completion_result, indent=2))+ try:+ chat_completion_result = llm_wrapper.output_to_chat_completion_response(result)+ if DEBUG:+ print(json.dumps(chat_completion_result, indent=2))+ except Exception as e:+ raise LocalLLMError(f"Failed to parse JSON from local LLM response - error: {str(e)}")# unpack with response.choices[0].message.contentresponse = DotDict(diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py b/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.pyindex 7bd793e36..c2224baab 100644--- a/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py+++ b/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py@@ -1,6 +1,7 @@import jsonfrom .wrapper_base import LLMChatCompletionWrapper+from ...errors import LLMJSONParsingErrorclass Airoboros21Wrapper(LLMChatCompletionWrapper):@@ -186,8 +187,11 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper):function_json_output = json.loads(raw_llm_output)except Exception as e:raise Exception(f"Failed to decode JSON from LLM output:\n{raw_llm_output}")- function_name = function_json_output["function"]- function_parameters = function_json_output["params"]+ try:+ function_name = function_json_output["function"]+ function_parameters = function_json_output["params"]+ except KeyError as e:+ raise LLMJSONParsingError(f"Received valid JSON from LLM, but JSON was missing fields: {str(e)}")if self.clean_func_args:function_name, function_parameters = self.clean_function_args(function_name, function_parameters)@@ -395,8 +399,11 @@ class Airoboros21InnerMonologueWrapper(Airoboros21Wrapper):function_json_output = json.loads(raw_llm_output + "\n}")except:raise Exception(f"Failed to decode JSON from LLM output:\n{raw_llm_output}")- function_name = function_json_output["function"]- function_parameters = function_json_output["params"]+ try:+ function_name = function_json_output["function"]+ function_parameters = function_json_output["params"]+ except KeyError as e:+ raise LLMJSONParsingError(f"Received valid JSON from LLM, but JSON was missing fields: {str(e)}")if self.clean_func_args:(diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/dolphin.py b/memgpt/local_llm/llm_chat_completion_wrappers/dolphin.pyindex 40d98579a..7d6206900 100644--- a/memgpt/local_llm/llm_chat_completion_wrappers/dolphin.py+++ b/memgpt/local_llm/llm_chat_completion_wrappers/dolphin.py@@ -1,6 +1,7 @@import jsonfrom .wrapper_base import LLMChatCompletionWrapper+from ...errors import LLMJSONParsingErrorclass Dolphin21MistralWrapper(LLMChatCompletionWrapper):@@ -221,8 +222,11 @@ class Dolphin21MistralWrapper(LLMChatCompletionWrapper):function_json_output = json.loads(raw_llm_output)except Exception as e:raise Exception(f"Failed to decode JSON from LLM output:\n{raw_llm_output}")- function_name = function_json_output["function"]- function_parameters = function_json_output["params"]+ try:+ function_name = function_json_output["function"]+ function_parameters = function_json_output["params"]+ except KeyError as e:+ raise LLMJSONParsingError(f"Received valid JSON from LLM, but JSON was missing fields: {str(e)}")if self.clean_func_args:function_name, function_parameters = self.clean_function_args(function_name, function_parameters)diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/simple_summary_wrapper.py b/memgpt/local_llm/llm_chat_completion_wrappers/simple_summary_wrapper.pynew file mode 100644index 000000000..fa027a16b--- /dev/null+++ b/memgpt/local_llm/llm_chat_completion_wrappers/simple_summary_wrapper.py@@ -0,0 +1,153 @@+import json+from .wrapper_base import LLMChatCompletionWrapper+++class SimpleSummaryWrapper(LLMChatCompletionWrapper):+ """A super basic wrapper that's meant to be used for summary generation only"""++ def __init__(+ self,+ simplify_json_content=True,+ include_assistant_prefix=True,+ # include_assistant_prefix=False, # False here, because we launch directly into summary+ include_section_separators=True,+ ):+ self.simplify_json_content = simplify_json_content+ self.include_assistant_prefix = include_assistant_prefix+ self.include_section_separators = include_section_separators++ def chat_completion_to_prompt(self, messages, functions):+ """Example for airoboros: https://huggingface.co/jondurbin/airoboros-l2-70b-2.1#prompt-format++ Instructions on how to summarize+ USER: {prompt}+ ASSISTANT:++ Functions support: https://huggingface.co/jondurbin/airoboros-l2-70b-2.1#agentfunction-calling++ As an AI assistant, please select the most suitable function and parameters from the list of available functions below, based on the user's input. Provide your response in JSON format.++ Input: I want to know how many times 'Python' is mentioned in my text file.++ Available functions:+ file_analytics:+ description: This tool performs various operations on a text file.+ params:+ action: The operation we want to perform on the data, such as "count_occurrences", "find_line", etc.+ filters:+ keyword: The word or phrase we want to search for.++ OpenAI functions schema style:++ {+ "name": "send_message",+ "description": "Sends a message to the human user",+ "parameters": {+ "type": "object",+ "properties": {+ # https://json-schema.org/understanding-json-schema/reference/array.html+ "message": {+ "type": "string",+ "description": "Message contents. All unicode (including emojis) are supported.",+ },+ },+ "required": ["message"],+ }+ },+ """+ assert functions is None+ prompt = ""++ # System insturctions go first+ assert messages[0]["role"] == "system"+ prompt += messages[0]["content"]++ def create_function_call(function_call):+ """Go from ChatCompletion to Airoboros style function trace (in prompt)++ ChatCompletion data (inside message['function_call']):+ "function_call": {+ "name": ...+ "arguments": {+ "arg1": val1,+ ...+ }++ Airoboros output:+ {+ "function": "send_message",+ "params": {+ "message": "Hello there! I am Sam, an AI developed by Liminal Corp. How can I assist you today?"+ }+ }+ """+ airo_func_call = {+ "function": function_call["name"],+ "params": json.loads(function_call["arguments"]),+ }+ return json.dumps(airo_func_call, indent=2)++ # Add a sep for the conversation+ if self.include_section_separators:+ prompt += "\n### INPUT"++ # Last are the user/assistant messages+ for message in messages[1:]:+ assert message["role"] in ["user", "assistant", "function"], message++ if message["role"] == "user":+ if self.simplify_json_content:+ try:+ content_json = json.loads(message["content"])+ content_simple = content_json["message"]+ prompt += f"\nUSER: {content_simple}"+ except:+ prompt += f"\nUSER: {message['content']}"+ elif message["role"] == "assistant":+ prompt += f"\nASSISTANT: {message['content']}"+ # need to add the function call if there was one+ if message["function_call"]:+ prompt += f"\n{create_function_call(message['function_call'])}"+ elif message["role"] == "function":+ # TODO find a good way to add this+ # prompt += f"\nASSISTANT: (function return) {message['content']}"+ prompt += f"\nFUNCTION RETURN: {message['content']}"+ continue+ else:+ raise ValueError(message)++ # Add a sep for the response+ if self.include_section_separators:+ prompt += "\n### RESPONSE (your summary of the above conversation in plain English (no JSON!), do NOT exceed the word limit)"++ if self.include_assistant_prefix:+ # prompt += f"\nASSISTANT:"+ prompt += f"\nSUMMARY:"++ # print(prompt)+ return prompt++ def output_to_chat_completion_response(self, raw_llm_output):+ """Turn raw LLM output into a ChatCompletion style response with:+ "message" = {+ "role": "assistant",+ "content": ...,+ "function_call": {+ "name": ...+ "arguments": {+ "arg1": val1,+ ...+ }+ }+ }+ """+ raw_llm_output = raw_llm_output.strip()+ message = {+ "role": "assistant",+ "content": raw_llm_output,+ # "function_call": {+ # "name": function_name,+ # "arguments": json.dumps(function_parameters),+ # },+ }+ return messagediff --git a/memgpt/local_llm/llm_chat_completion_wrappers/zephyr.py b/memgpt/local_llm/llm_chat_completion_wrappers/zephyr.pyindex b088e50ac..542da3ce5 100644--- a/memgpt/local_llm/llm_chat_completion_wrappers/zephyr.py+++ b/memgpt/local_llm/llm_chat_completion_wrappers/zephyr.py@@ -1,5 +1,6 @@import jsonfrom .wrapper_base import LLMChatCompletionWrapper+from ...errors import LLMJSONParsingErrorclass ZephyrMistralWrapper(LLMChatCompletionWrapper):@@ -151,8 +152,11 @@ class ZephyrMistralWrapper(LLMChatCompletionWrapper):function_json_output = json.loads(raw_llm_output)except Exception as e:raise Exception(f"Failed to decode JSON from LLM output:\n{raw_llm_output}")- function_name = function_json_output["function"]- function_parameters = function_json_output["params"]+ try:+ function_name = function_json_output["function"]+ function_parameters = function_json_output["params"]+ except KeyError as e:+ raise LLMJSONParsingError(f"Received valid JSON from LLM, but JSON was missing fields: {str(e)}")if self.clean_func_args:function_name, function_parameters = self.clean_function_args(function_name, function_parameters)@@ -314,8 +318,11 @@ class ZephyrMistralInnerMonologueWrapper(ZephyrMistralWrapper):function_json_output = json.loads(raw_llm_output + "\n}")except:raise Exception(f"Failed to decode JSON from LLM output:\n{raw_llm_output}")- function_name = function_json_output["function"]- function_parameters = function_json_output["params"]+ try:+ function_name = function_json_output["function"]+ function_parameters = function_json_output["params"]+ except KeyError as e:+ raise LLMJSONParsingError(f"Received valid JSON from LLM, but JSON was missing fields: {str(e)}")if self.clean_func_args:(diff --git a/memgpt/local_llm/lmstudio/settings.py b/memgpt/local_llm/lmstudio/settings.pyindex 3d8622ace..dab059373 100644--- a/memgpt/local_llm/lmstudio/settings.py+++ b/memgpt/local_llm/lmstudio/settings.py@@ -1,3 +1,5 @@+from ...constants import LLM_MAX_TOKENS+SIMPLE = {"stop": ["\nUSER:",@@ -11,7 +13,8 @@ SIMPLE = {],# This controls the maximum number of tokens that the model can generate# Cap this at the model context length (assuming 8k for Mistral 7B)- "max_tokens": 8000,+ # "max_tokens": 8000,+ "max_tokens": LLM_MAX_TOKENS,# This controls how LM studio handles context overflow# In MemGPT we handle this ourselves, so this should be commented out# "lmstudio": {"context_overflow_policy": 2},diff --git a/memgpt/local_llm/webui/api.py b/memgpt/local_llm/webui/api.pyindex abe2d36d6..82fdc0ce5 100644--- a/memgpt/local_llm/webui/api.py+++ b/memgpt/local_llm/webui/api.py@@ -1,17 +1,28 @@import osfrom urllib.parse import urljoinimport requests+import tiktokenfrom .settings import SIMPLE+from ...constants import LLM_MAX_TOKENS+HOST = os.getenv("OPENAI_API_BASE")HOST_TYPE = os.getenv("BACKEND_TYPE") # default None == ChatCompletionWEBUI_API_SUFFIX = "/api/v1/generate"DEBUG = False+def count_tokens(s: str, model: str = "gpt-4") -> int:+ encoding = tiktoken.encoding_for_model(model)+ return len(encoding.encode(s))++def get_webui_completion(prompt, settings=SIMPLE):"""See https://github.com/oobabooga/text-generation-webui for instructions on how to run the LLM web server"""+ prompt_tokens = count_tokens(prompt)+ if prompt_tokens > LLM_MAX_TOKENS:+ raise Exception(f"Request exceeds maximum context length ({prompt_tokens} > {LLM_MAX_TOKENS} tokens)")# Settings for the generation, includes the prompt + stop tokens, max length, etcrequest = settings@@ -30,8 +41,10 @@ def get_webui_completion(prompt, settings=SIMPLE):print(f"json API response.text: {result}")else:raise Exception(- f"API call got non-200 response code for address: {URI}. Make sure that the web UI server is running and reachable at {URI}."+ f"API call got non-200 response code (code={response.status_code}, msg={response.text}) for address: {URI}."+ + f"Make sure that the web UI server is running and reachable at {URI}.")+except:# TODO handle gracefullyraisediff --git a/memgpt/local_llm/webui/settings.py b/memgpt/local_llm/webui/settings.pyindex ba1ee9c17..dd89b68bb 100644--- a/memgpt/local_llm/webui/settings.py+++ b/memgpt/local_llm/webui/settings.py@@ -1,3 +1,5 @@+from ...constants import LLM_MAX_TOKENS+SIMPLE = {"stopping_strings": ["\nUSER:",@@ -11,5 +13,5 @@ SIMPLE = {],"max_new_tokens": 3072,# "truncation_length": 4096, # assuming llama2 models- "truncation_length": 8000, # assuming mistral 7b+ "truncation_length": LLM_MAX_TOKENS, # assuming mistral 7b}diff --git a/memgpt/memory.py b/memgpt/memory.pyindex 1698a4d16..921520cd1 100644--- a/memgpt/memory.py+++ b/memgpt/memory.py@@ -121,7 +121,7 @@ def summarize_messages(summary_prompt = SUMMARY_PROMPT_SYSTEMsummary_input = str(message_sequence_to_summarize)- summary_input_tkns = count_tokens(summary_input, model)+ summary_input_tkns = count_tokens(summary_input)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)@@ -149,12 +149,12 @@ async def a_summarize_messages(summary_prompt = SUMMARY_PROMPT_SYSTEMsummary_input = str(message_sequence_to_summarize)- summary_input_tkns = count_tokens(summary_input, model)+ summary_input_tkns = count_tokens(summary_input)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(- [await summarize_messages(model, message_sequence_to_summarize[:cutoff])] + message_sequence_to_summarize[cutoff:]+ [await a_summarize_messages(model, message_sequence_to_summarize[:cutoff])] + message_sequence_to_summarize[cutoff:])message_sequence = [{"role": "system", "content": summary_prompt},