Platform for stateful agents: AI with advanced memory that can learn and self-improve over time.
add comment about no inner mono + blackified the code
Charles Packerf4ae08f6f5fa
diff --git a/memgpt/local_llm/chat_completion_proxy.py b/memgpt/local_llm/chat_completion_proxy.pyindex 39f69109e..ea5b904f6 100644--- a/memgpt/local_llm/chat_completion_proxy.py+++ b/memgpt/local_llm/chat_completion_proxy.py@@ -13,8 +13,8 @@ import requestsfrom .webui_settings import DETERMINISTIC, SIMPLEfrom .llm_chat_completion_wrappers import airoboros-HOST = os.getenv('OPENAI_API_BASE')-HOST_TYPE = os.getenv('BACKEND_TYPE') # default None == ChatCompletion+HOST = os.getenv("OPENAI_API_BASE")+HOST_TYPE = os.getenv("BACKEND_TYPE") # default None == ChatCompletionclass DotDict(dict):@@ -28,36 +28,35 @@ class DotDict(dict):async def get_chat_completion(- model, # no model, since the model is fixed to whatever you set in your own backend- messages,- functions,- function_call="auto",- ):+ model, # no model, since the model is fixed to whatever you set in your own backend+ messages,+ functions,+ function_call="auto",+):if function_call != "auto":raise ValueError(f"function_call == {function_call} not supported (auto only)")- if True or model == 'airoboros_v2.1':+ if True or model == "airoboros_v2.1":llm_wrapper = airoboros.Airoboros21Wrapper()# First step: turn the message sequence into a prompt that the model expectsprompt = llm_wrapper.chat_completion_to_prompt(messages, functions)# print(prompt)- if HOST_TYPE != 'webui':+ if HOST_TYPE != "webui":raise ValueError(HOST_TYPE)request = SIMPLE- request['prompt'] = prompt+ request["prompt"] = prompttry:-- URI = f'{HOST}/v1/generate'+ URI = f"{HOST}/v1/generate"response = requests.post(URI, json=request)if response.status_code == 200:# result = response.json()['results'][0]['history']result = response.json()# print(f"raw API response: {result}")- result = result['results'][0]['text']+ result = result["results"][0]["text"]print(f"json API response.text: {result}")else:raise Exception(f"API call got non-200 response code")@@ -68,19 +67,27 @@ async def get_chat_completion(# print(cleaned_result)# unpack with response.choices[0].message.content- response = DotDict({- 'model': None,- 'choices': [DotDict({- 'message': DotDict(chat_completion_result),- 'finish_reason': 'stop', # TODO vary based on webui response- })],- 'usage': DotDict({- # TODO fix- 'prompt_tokens': 0,- 'completion_tokens': 0,- 'total_tokens': 0,- })- })+ response = DotDict(+ {+ "model": None,+ "choices": [+ DotDict(+ {+ "message": DotDict(chat_completion_result),+ "finish_reason": "stop", # TODO vary based on webui response+ }+ )+ ],+ "usage": DotDict(+ {+ # TODO fix+ "prompt_tokens": 0,+ "completion_tokens": 0,+ "total_tokens": 0,+ }+ ),+ }+ )return responseexcept Exception as e:diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py b/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.pyindex 303e2d37d..6b3a117f8 100644--- a/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py+++ b/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py@@ -5,9 +5,16 @@ from .wrapper_base import LLMChatCompletionWrapperclass Airoboros21Wrapper(LLMChatCompletionWrapper):"""Wrapper for Airoboros 70b v2.1: https://huggingface.co/jondurbin/airoboros-l2-70b-2.1++ Note: this wrapper formats a prompt that only generates JSON, no inner thoughts"""- def __init__(self, simplify_json_content=True, include_assistant_prefix=True, clean_function_args=True):+ def __init__(+ self,+ simplify_json_content=True,+ include_assistant_prefix=True,+ clean_function_args=True,+ ):self.simplify_json_content = simplify_json_contentself.include_assistant_prefix = include_assistant_prefixself.clean_func_args = clean_function_args@@ -54,8 +61,8 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper):prompt = ""# System insturctions go first- assert messages[0]['role'] == 'system'- prompt += messages[0]['content']+ assert messages[0]["role"] == "system"+ prompt += messages[0]["content"]# Next is the functions preambledef create_function_description(schema):@@ -64,7 +71,7 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper):func_str += f"{schema['name']}:"func_str += f"\n description: {schema['description']}"func_str += f"\n params:"- for param_k, param_v in schema['parameters']['properties'].items():+ for param_k, param_v in schema["parameters"]["properties"].items():# TODO we're ignoring typefunc_str += f"\n {param_k}: {param_v['description']}"# TODO we're ignoring schema['parameters']['required']@@ -77,19 +84,19 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper):# Last are the user/assistant messagesfor message in messages[1:]:- assert message['role'] in ['user', 'assistant', 'function'], message+ assert message["role"] in ["user", "assistant", "function"], message- if message['role'] == 'user':+ if message["role"] == "user":if self.simplify_json_content:try:- content_json = json.loads(message['content'])- content_simple = content_json['message']+ 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':+ elif message["role"] == "assistant":prompt += f"\nASSISTANT: {message['content']}"- elif message['role'] == 'function':+ elif message["role"] == "function":# TODOcontinue# prompt += f"\nASSISTANT: (function return) {message['content']}"@@ -107,9 +114,9 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper):cleaned_function_name = function_namecleaned_function_args = function_args.copy()- if function_name == 'send_message':+ if function_name == "send_message":# strip request_heartbeat- cleaned_function_args.pop('request_heartbeat', None)+ cleaned_function_args.pop("request_heartbeat", None)# TODO more cleaning to fix errors LLM makesreturn cleaned_function_name, cleaned_function_args@@ -129,18 +136,20 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper):}"""function_json_output = json.loads(raw_llm_output)- function_name = function_json_output['function']- function_parameters = function_json_output['params']+ function_name = function_json_output["function"]+ function_parameters = function_json_output["params"]if self.clean_func_args:- function_name, function_parameters = self.clean_function_args(function_name, function_parameters)+ function_name, function_parameters = self.clean_function_args(+ function_name, function_parameters+ )message = {- 'role': 'assistant',- 'content': None,- 'function_call': {- 'name': function_name,- 'arguments': json.dumps(function_parameters),- }+ "role": "assistant",+ "content": None,+ "function_call": {+ "name": function_name,+ "arguments": json.dumps(function_parameters),+ },}return messagediff --git a/memgpt/local_llm/llm_chat_completion_wrappers/wrapper_base.py b/memgpt/local_llm/llm_chat_completion_wrappers/wrapper_base.pyindex d2e7584e9..b1186c468 100644--- a/memgpt/local_llm/llm_chat_completion_wrappers/wrapper_base.py+++ b/memgpt/local_llm/llm_chat_completion_wrappers/wrapper_base.py@@ -2,7 +2,6 @@ from abc import ABC, abstractmethodclass LLMChatCompletionWrapper(ABC):-@abstractmethoddef chat_completion_to_prompt(self, messages, functions):"""Go from ChatCompletion to a single prompt string"""diff --git a/memgpt/local_llm/webui_settings.py b/memgpt/local_llm/webui_settings.pyindex dc5780847..2601f6425 100644--- a/memgpt/local_llm/webui_settings.py+++ b/memgpt/local_llm/webui_settings.py@@ -1,54 +1,54 @@DETERMINISTIC = {- 'max_new_tokens': 250,- 'do_sample': False,- 'temperature': 0,- 'top_p': 0,- 'typical_p': 1,- 'repetition_penalty': 1.18,- 'repetition_penalty_range': 0,- 'encoder_repetition_penalty': 1,- 'top_k': 1,- 'min_length': 0,- 'no_repeat_ngram_size': 0,- 'num_beams': 1,- 'penalty_alpha': 0,- 'length_penalty': 1,- 'early_stopping': False,- 'guidance_scale': 1,- 'negative_prompt': '',- 'seed': -1,- 'add_bos_token': True,- 'stopping_strings': [- '\nUSER:',- '\nASSISTANT:',+ "max_new_tokens": 250,+ "do_sample": False,+ "temperature": 0,+ "top_p": 0,+ "typical_p": 1,+ "repetition_penalty": 1.18,+ "repetition_penalty_range": 0,+ "encoder_repetition_penalty": 1,+ "top_k": 1,+ "min_length": 0,+ "no_repeat_ngram_size": 0,+ "num_beams": 1,+ "penalty_alpha": 0,+ "length_penalty": 1,+ "early_stopping": False,+ "guidance_scale": 1,+ "negative_prompt": "",+ "seed": -1,+ "add_bos_token": True,+ "stopping_strings": [+ "\nUSER:",+ "\nASSISTANT:",# '\n' +# '</s>',# '<|',# '\n#',# '\n\n\n',- ],- 'truncation_length': 4096,- 'ban_eos_token': False,- 'skip_special_tokens': True,- 'top_a': 0,- 'tfs': 1,- 'epsilon_cutoff': 0,- 'eta_cutoff': 0,- 'mirostat_mode': 2,- 'mirostat_tau': 4,- 'mirostat_eta': 0.1,- 'use_mancer': False- }+ ],+ "truncation_length": 4096,+ "ban_eos_token": False,+ "skip_special_tokens": True,+ "top_a": 0,+ "tfs": 1,+ "epsilon_cutoff": 0,+ "eta_cutoff": 0,+ "mirostat_mode": 2,+ "mirostat_tau": 4,+ "mirostat_eta": 0.1,+ "use_mancer": False,+}SIMPLE = {- 'stopping_strings': [- '\nUSER:',- '\nASSISTANT:',+ "stopping_strings": [+ "\nUSER:",+ "\nASSISTANT:",# '\n' +# '</s>',# '<|',# '\n#',# '\n\n\n',- ],- 'truncation_length': 4096,-}\ No newline at end of file+ ],+ "truncation_length": 4096,+}diff --git a/memgpt/openai_tools.py b/memgpt/openai_tools.pyindex 7729ae155..3d63d1346 100644--- a/memgpt/openai_tools.py+++ b/memgpt/openai_tools.py@@ -4,10 +4,12 @@ import osimport timefrom .local_llm.chat_completion_proxy import get_chat_completion-HOST = os.getenv('OPENAI_API_BASE')-HOST_TYPE = os.getenv('BACKEND_TYPE') # default None == ChatCompletion++HOST = os.getenv("OPENAI_API_BASE")+HOST_TYPE = os.getenv("BACKEND_TYPE") # default None == ChatCompletionimport openai+if HOST is not None:openai.api_base = HOST@@ -108,25 +110,24 @@ def aretry_with_exponential_backoff(@aretry_with_exponential_backoffasync def acompletions_with_backoff(**kwargs):-# Local modelif HOST_TYPE is not None:return await get_chat_completion(**kwargs)# OpenAI / Azure modelelse:- azure_openai_deployment = os.getenv('AZURE_OPENAI_DEPLOYMENT')+ azure_openai_deployment = os.getenv("AZURE_OPENAI_DEPLOYMENT")if azure_openai_deployment is not None:- kwargs['deployment_id'] = azure_openai_deployment+ kwargs["deployment_id"] = azure_openai_deploymentreturn await openai.ChatCompletion.acreate(**kwargs)@aretry_with_exponential_backoffasync def acreate_embedding_with_backoff(**kwargs):"""Wrapper around Embedding.acreate w/ backoff"""- azure_openai_deployment = os.getenv('AZURE_OPENAI_DEPLOYMENT')+ azure_openai_deployment = os.getenv("AZURE_OPENAI_DEPLOYMENT")if azure_openai_deployment is not None:- kwargs['deployment_id'] = azure_openai_deployment+ kwargs["deployment_id"] = azure_openai_deploymentreturn await openai.Embedding.acreate(**kwargs)@@ -134,6 +135,6 @@ async def async_get_embedding_with_backoff(text, model="text-embedding-ada-002")"""To get text embeddings, import/call this functionIt specifies defaults + handles rate-limiting + is async"""text = text.replace("\n", " ")- response = await acreate_embedding_with_backoff(input = [text], model=model)- embedding = response['data'][0]['embedding']- return embedding\ No newline at end of file+ response = await acreate_embedding_with_backoff(input=[text], model=model)+ embedding = response["data"][0]["embedding"]+ return embedding