From 8484f0557d76cc84ed4ae9dd8eb1f86322463b3e Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Sun, 22 Oct 2023 22:52:24 -0700 Subject: [PATCH 01/21] basic proof of concept tested on airoboros 70b 2.1 --- memgpt/local_llm/README.md | 3 + memgpt/local_llm/__init__.py | 0 memgpt/local_llm/chat_completion_proxy.py | 88 +++++++++++ .../llm_chat_completion_wrappers/__init__.py | 0 .../llm_chat_completion_wrappers/airoboros.py | 146 ++++++++++++++++++ .../wrapper_base.py | 14 ++ memgpt/local_llm/webui_settings.py | 54 +++++++ memgpt/openai_tools.py | 21 ++- 8 files changed, 322 insertions(+), 4 deletions(-) create mode 100644 memgpt/local_llm/README.md create mode 100644 memgpt/local_llm/__init__.py create mode 100644 memgpt/local_llm/chat_completion_proxy.py create mode 100644 memgpt/local_llm/llm_chat_completion_wrappers/__init__.py create mode 100644 memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py create mode 100644 memgpt/local_llm/llm_chat_completion_wrappers/wrapper_base.py create mode 100644 memgpt/local_llm/webui_settings.py diff --git a/memgpt/local_llm/README.md b/memgpt/local_llm/README.md new file mode 100644 index 00000000..d81a58e7 --- /dev/null +++ b/memgpt/local_llm/README.md @@ -0,0 +1,3 @@ +## TODO + +Instructions on how to add additional support for other function calling LLMs + other LLM backends \ No newline at end of file diff --git a/memgpt/local_llm/__init__.py b/memgpt/local_llm/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memgpt/local_llm/chat_completion_proxy.py b/memgpt/local_llm/chat_completion_proxy.py new file mode 100644 index 00000000..39f69109 --- /dev/null +++ b/memgpt/local_llm/chat_completion_proxy.py @@ -0,0 +1,88 @@ +"""MemGPT sends a ChatCompletion request + +Under the hood, we use the functions argument to turn +""" + + +"""Key idea: create drop-in replacement for agent's ChatCompletion call that runs on an OpenLLM backend""" + +import os +import json +import requests + +from .webui_settings import DETERMINISTIC, SIMPLE +from .llm_chat_completion_wrappers import airoboros + +HOST = os.getenv('OPENAI_API_BASE') +HOST_TYPE = os.getenv('BACKEND_TYPE') # default None == ChatCompletion + + +class DotDict(dict): + """Allow dot access on properties similar to OpenAI response object""" + + def __getattr__(self, attr): + return self.get(attr) + + def __setattr__(self, key, value): + self[key] = value + + +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", + ): + if function_call != "auto": + raise ValueError(f"function_call == {function_call} not supported (auto only)") + + if True or model == 'airoboros_v2.1': + llm_wrapper = airoboros.Airoboros21Wrapper() + + # First step: turn the message sequence into a prompt that the model expects + prompt = llm_wrapper.chat_completion_to_prompt(messages, functions) + # print(prompt) + + if HOST_TYPE != 'webui': + raise ValueError(HOST_TYPE) + + request = SIMPLE + request['prompt'] = prompt + + try: + + 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'] + print(f"json API response.text: {result}") + else: + raise Exception(f"API call got non-200 response code") + + # cleaned_result, chatcompletion_result = parse_st_json_output(result) + chat_completion_result = llm_wrapper.output_to_chat_completion_response(result) + print(json.dumps(chat_completion_result, indent=2)) + # 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, + }) + }) + return response + + except Exception as e: + # TODO + raise e diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/__init__.py b/memgpt/local_llm/llm_chat_completion_wrappers/__init__.py new file mode 100644 index 00000000..e69de29b diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py b/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py new file mode 100644 index 00000000..303e2d37 --- /dev/null +++ b/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py @@ -0,0 +1,146 @@ +import json + +from .wrapper_base import LLMChatCompletionWrapper + + +class Airoboros21Wrapper(LLMChatCompletionWrapper): + """Wrapper for Airoboros 70b v2.1: https://huggingface.co/jondurbin/airoboros-l2-70b-2.1 + """ + + def __init__(self, simplify_json_content=True, include_assistant_prefix=True, clean_function_args=True): + self.simplify_json_content = simplify_json_content + self.include_assistant_prefix = include_assistant_prefix + self.clean_func_args = clean_function_args + + def chat_completion_to_prompt(self, messages, functions): + """Example for airoboros: https://huggingface.co/jondurbin/airoboros-l2-70b-2.1#prompt-format + + A chat. + 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"], + } + }, + """ + prompt = "" + + # System insturctions go first + assert messages[0]['role'] == 'system' + prompt += messages[0]['content'] + + # Next is the functions preamble + def create_function_description(schema): + # airorobos style + func_str = "" + 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(): + # TODO we're ignoring type + func_str += f"\n {param_k}: {param_v['description']}" + # TODO we're ignoring schema['parameters']['required'] + return func_str + + prompt += f"\nPlease 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." + prompt += f"\nAvailable functions:" + for function_dict in functions: + prompt += f"\n{create_function_description(function_dict)}" + + # 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']}" + elif message['role'] == 'function': + # TODO + continue + # prompt += f"\nASSISTANT: (function return) {message['content']}" + else: + raise ValueError(message) + + if self.include_assistant_prefix: + # prompt += f"\nPlease 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." + prompt += f"\nASSISTANT:" + + return prompt + + def clean_function_args(self, function_name, function_args): + """Some basic MemGPT-specific cleaning of function args""" + cleaned_function_name = function_name + cleaned_function_args = function_args.copy() + + if function_name == 'send_message': + # strip request_heartbeat + cleaned_function_args.pop('request_heartbeat', None) + + # TODO more cleaning to fix errors LLM makes + return cleaned_function_name, cleaned_function_args + + 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, + ... + } + } + } + """ + function_json_output = json.loads(raw_llm_output) + 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) + + message = { + 'role': 'assistant', + 'content': None, + 'function_call': { + 'name': function_name, + 'arguments': json.dumps(function_parameters), + } + } + return message diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/wrapper_base.py b/memgpt/local_llm/llm_chat_completion_wrappers/wrapper_base.py new file mode 100644 index 00000000..d2e7584e --- /dev/null +++ b/memgpt/local_llm/llm_chat_completion_wrappers/wrapper_base.py @@ -0,0 +1,14 @@ +from abc import ABC, abstractmethod + + +class LLMChatCompletionWrapper(ABC): + + @abstractmethod + def chat_completion_to_prompt(self, messages, functions): + """Go from ChatCompletion to a single prompt string""" + pass + + @abstractmethod + def output_to_chat_completion_response(self, raw_llm_output): + """Turn the LLM output string into a ChatCompletion response""" + pass diff --git a/memgpt/local_llm/webui_settings.py b/memgpt/local_llm/webui_settings.py new file mode 100644 index 00000000..dc578084 --- /dev/null +++ b/memgpt/local_llm/webui_settings.py @@ -0,0 +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:', + # '\n' + + # '', + # '<|', + # '\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 + } + +SIMPLE = { + 'stopping_strings': [ + '\nUSER:', + '\nASSISTANT:', + # '\n' + + # '', + # '<|', + # '\n#', + # '\n\n\n', + ], + 'truncation_length': 4096, +} \ No newline at end of file diff --git a/memgpt/openai_tools.py b/memgpt/openai_tools.py index 98444878..7729ae15 100644 --- a/memgpt/openai_tools.py +++ b/memgpt/openai_tools.py @@ -3,7 +3,13 @@ import random import os import time +from .local_llm.chat_completion_proxy import get_chat_completion +HOST = os.getenv('OPENAI_API_BASE') +HOST_TYPE = os.getenv('BACKEND_TYPE') # default None == ChatCompletion + import openai +if HOST is not None: + openai.api_base = HOST def retry_with_exponential_backoff( @@ -102,10 +108,17 @@ def aretry_with_exponential_backoff( @aretry_with_exponential_backoff async def acompletions_with_backoff(**kwargs): - azure_openai_deployment = os.getenv('AZURE_OPENAI_DEPLOYMENT') - if azure_openai_deployment is not None: - kwargs['deployment_id'] = azure_openai_deployment - return await openai.ChatCompletion.acreate(**kwargs) + + # Local model + if HOST_TYPE is not None: + return await get_chat_completion(**kwargs) + + # OpenAI / Azure model + else: + azure_openai_deployment = os.getenv('AZURE_OPENAI_DEPLOYMENT') + if azure_openai_deployment is not None: + kwargs['deployment_id'] = azure_openai_deployment + return await openai.ChatCompletion.acreate(**kwargs) @aretry_with_exponential_backoff From 172ddc4423a6e0b5253e47ebecc94e9b0fc00d91 Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Sun, 22 Oct 2023 23:09:41 -0700 Subject: [PATCH 02/21] Update README.md --- memgpt/local_llm/README.md | 36 ++++++++++++++++++++++++++++++++++-- 1 file changed, 34 insertions(+), 2 deletions(-) diff --git a/memgpt/local_llm/README.md b/memgpt/local_llm/README.md index d81a58e7..f23bbc70 100644 --- a/memgpt/local_llm/README.md +++ b/memgpt/local_llm/README.md @@ -1,3 +1,35 @@ -## TODO +## tl;dr - how to connect MemGPT to non-OpenAI LLMs -Instructions on how to add additional support for other function calling LLMs + other LLM backends \ No newline at end of file +**If you have a hosted ChatCompletion-compatible endpoint that works with function calling**: + - simply set `OPENAI_API_BASE` to the IP+port of your endpoint: + +```sh +export OPENAI_API_BASE=... +``` + +Note: for this to work, the endpoint MUST support function calls. As of 10/22/2023, most ChatCompletion endpoints do NOT support function calls, so if you want to play with MemGPT and open models, follow the instructions below. + +**If you have a hosted local model that is function-call finetuned**: + - implement a wrapper class for that model + - the wrapper class needs to implement two functions: + - one to go from ChatCompletion messages/functions schema to a prompt string + - and one to go from raw LLM outputs to a ChatCompletion response + - put that model behind a server (e.g. using WebUI) and set `OPENAI_API_BASE` + +To help you get started, we've implemented an example wrapper class for a popular llama2 model finetuned on function calling (airoboros). We want MemGPT to run well on open models as much as you do, so we'll be actively updating this page with more examples. Additionally, we welcome contributions from the community! If you find an open LLM that works well with MemGPT, please open a PR with a model wrapper and we'll merge it ASAP. + +## Status of ChatCompletion w/ function calling and open LLMs + +MemGPT uses function calling to do memory management. With OpenAI's ChatCompletion API, you can pass in a function schema in the ‘functions' keyword arg, and the API response will include a ‘function_call’ field that includes the function name and the function arguments (generated JSON). How this works under the hood is your ‘functions’ keyword is combined with the ‘messages’ and ‘system' to form one big string input to the transformer, and the output of the transformer is parsed to extract the JSON function call. + +In the future, more open LLMs and LLM servers (that can host OpenAI-compatable ChatCompletion endpoints) may start including parsing code to do this automatically as standard practice. However, in the meantime, when you see a model that says it supports “function calling”, like Airoboros, it doesn't mean that you can just load Airoboros into a ChatCompletion-compatable endpoint like FastChat, and then use the same OpenAI API call and it'll just work. + +(1) When an open LLM says it supports function calling, they probably mean that the model was finetuned on some function call data. Remember, transformers are just string-in-string-out, so there are many ways to format this function call data. Airoboros formats the function schema in YAML style (see https://huggingface.co/jondurbin/airoboros-l2-70b-3.1.2#agentfunction-calling)) and the output is in JSON style. To get this to work behind a ChatCompletion API, you still have to do the parsing from ‘functions’ keyword arg (containing the schema) to the model's expected schema style in the prompt (YAML for Airoboros), and you have to run some code to extract the function call (JSON for Airoboros) and package it cleanly as a ‘function_call’ field in the response. + +(2) Partly because of how complex it is to support function calling, most (all?) of the community projects that do OpenAI ChatCompletion endpoints for arbitrary open LLMs do not support function calling, because if they did, they would need to write model-specific parsing code for each one. + +## How can you run MemGPT with open LLMs that support function calling? + +Because of the poor state of function calling support in existing ChatCompletion API serving code, we instead provide a light wrapper on top of ChatCompletion that uses a parser specific to Airoboros. We hope that this example code will help the community add additional compatability of MemGPT with more function-calling LLMs - we will also add more model support as we test more models and find those that work well enough to run MemGPT's function set. + +To run the example of MemGPT with Airoboros, you'll need to host the model with some open LLM hosting code, for example Oobagooba (see here). Then, all you need to do is point MemGPT to this API endpoint. Now, instead of calling ChatCompletion on OpenAI's API, MemGPT will use it's own ChatCompletion wrapper that parses the system, messages, and function arguments into a format that Airoboros has been finetuned on, and once Airoboros generates a string output, MemGPT will parse the response to extract a potential function call (knowing what we know about Airoboros expected function call output). From e4add84bbe62ff9472dc0a7c89c9b219940b92bc Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Sun, 22 Oct 2023 23:13:01 -0700 Subject: [PATCH 03/21] Update README.md --- memgpt/local_llm/README.md | 44 ++++++++++++++++++++++++++++++++++++++ 1 file changed, 44 insertions(+) diff --git a/memgpt/local_llm/README.md b/memgpt/local_llm/README.md index f23bbc70..a1f7b759 100644 --- a/memgpt/local_llm/README.md +++ b/memgpt/local_llm/README.md @@ -9,6 +9,8 @@ export OPENAI_API_BASE=... Note: for this to work, the endpoint MUST support function calls. As of 10/22/2023, most ChatCompletion endpoints do NOT support function calls, so if you want to play with MemGPT and open models, follow the instructions below. +## Integrating a function-call finetuned LLM with MemGPT + **If you have a hosted local model that is function-call finetuned**: - implement a wrapper class for that model - the wrapper class needs to implement two functions: @@ -16,8 +18,50 @@ Note: for this to work, the endpoint MUST support function calls. As of 10/22/20 - and one to go from raw LLM outputs to a ChatCompletion response - put that model behind a server (e.g. using WebUI) and set `OPENAI_API_BASE` +```python +class LLMChatCompletionWrapper(ABC): + + @abstractmethod + def chat_completion_to_prompt(self, messages, functions): + """Go from ChatCompletion to a single prompt string""" + pass + + @abstractmethod + def output_to_chat_completion_response(self, raw_llm_output): + """Turn the LLM output string into a ChatCompletion response""" + pass +``` + To help you get started, we've implemented an example wrapper class for a popular llama2 model finetuned on function calling (airoboros). We want MemGPT to run well on open models as much as you do, so we'll be actively updating this page with more examples. Additionally, we welcome contributions from the community! If you find an open LLM that works well with MemGPT, please open a PR with a model wrapper and we'll merge it ASAP. +```python +class Airoboros21Wrapper(LLMChatCompletionWrapper): + """Wrapper for Airoboros 70b v2.1: https://huggingface.co/jondurbin/airoboros-l2-70b-2.1""" + + def chat_completion_to_prompt(self, messages, functions): + """ + Examples for how airoboros expects its prompt inputs: https://huggingface.co/jondurbin/airoboros-l2-70b-2.1#prompt-format + Examples for how airoboros expects to see function schemas: https://huggingface.co/jondurbin/airoboros-l2-70b-2.1#agentfunction-calling + """ + + 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, + ... + } + } + } + """ +``` + +--- + ## Status of ChatCompletion w/ function calling and open LLMs MemGPT uses function calling to do memory management. With OpenAI's ChatCompletion API, you can pass in a function schema in the ‘functions' keyword arg, and the API response will include a ‘function_call’ field that includes the function name and the function arguments (generated JSON). How this works under the hood is your ‘functions’ keyword is combined with the ‘messages’ and ‘system' to form one big string input to the transformer, and the output of the transformer is parsed to extract the JSON function call. From c8b89e25d068d38e113c210c17ed9a00d13fb1e2 Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Sun, 22 Oct 2023 23:13:49 -0700 Subject: [PATCH 04/21] Update README.md --- memgpt/local_llm/README.md | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/memgpt/local_llm/README.md b/memgpt/local_llm/README.md index a1f7b759..a8c2304a 100644 --- a/memgpt/local_llm/README.md +++ b/memgpt/local_llm/README.md @@ -1,4 +1,4 @@ -## tl;dr - how to connect MemGPT to non-OpenAI LLMs +## How to connect MemGPT to non-OpenAI LLMs **If you have a hosted ChatCompletion-compatible endpoint that works with function calling**: - simply set `OPENAI_API_BASE` to the IP+port of your endpoint: @@ -7,7 +7,7 @@ export OPENAI_API_BASE=... ``` -Note: for this to work, the endpoint MUST support function calls. As of 10/22/2023, most ChatCompletion endpoints do NOT support function calls, so if you want to play with MemGPT and open models, follow the instructions below. +Note: for this to work, the endpoint **MUST** support function calls. As of 10/22/2023, most ChatCompletion endpoints do **NOT** support function calls, so if you want to play with MemGPT and open models, you probably need to follow the instructions below. ## Integrating a function-call finetuned LLM with MemGPT From 6f293c90f465f6f165038d7f41bd548bebfdc53e Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Sun, 22 Oct 2023 23:15:01 -0700 Subject: [PATCH 05/21] Update README.md --- memgpt/local_llm/README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/memgpt/local_llm/README.md b/memgpt/local_llm/README.md index a8c2304a..a82e2127 100644 --- a/memgpt/local_llm/README.md +++ b/memgpt/local_llm/README.md @@ -32,6 +32,8 @@ class LLMChatCompletionWrapper(ABC): pass ``` +## Example with Airoboros LLM + To help you get started, we've implemented an example wrapper class for a popular llama2 model finetuned on function calling (airoboros). We want MemGPT to run well on open models as much as you do, so we'll be actively updating this page with more examples. Additionally, we welcome contributions from the community! If you find an open LLM that works well with MemGPT, please open a PR with a model wrapper and we'll merge it ASAP. ```python From 7e103fcb63e50b6a731c9e59ff2ec25c17e016c6 Mon Sep 17 00:00:00 2001 From: Vivian Fang Date: Sun, 22 Oct 2023 23:35:52 -0700 Subject: [PATCH 06/21] Update README.md --- memgpt/local_llm/README.md | 21 ++++++++++++--------- 1 file changed, 12 insertions(+), 9 deletions(-) diff --git a/memgpt/local_llm/README.md b/memgpt/local_llm/README.md index a82e2127..69165305 100644 --- a/memgpt/local_llm/README.md +++ b/memgpt/local_llm/README.md @@ -7,16 +7,18 @@ export OPENAI_API_BASE=... ``` -Note: for this to work, the endpoint **MUST** support function calls. As of 10/22/2023, most ChatCompletion endpoints do **NOT** support function calls, so if you want to play with MemGPT and open models, you probably need to follow the instructions below. +For this to work, the endpoint **MUST** support function calls. + +**As of 10/22/2023, most ChatCompletion endpoints do *NOT* support function calls, so if you want to play with MemGPT and open models, you probably need to follow the instructions below.** ## Integrating a function-call finetuned LLM with MemGPT **If you have a hosted local model that is function-call finetuned**: - - implement a wrapper class for that model - - the wrapper class needs to implement two functions: - - one to go from ChatCompletion messages/functions schema to a prompt string - - and one to go from raw LLM outputs to a ChatCompletion response - - put that model behind a server (e.g. using WebUI) and set `OPENAI_API_BASE` + - Implement a wrapper class for that model + - The wrapper class needs to implement two functions: + - One to go from ChatCompletion messages/functions schema to a prompt string + - And one to go from raw LLM outputs to a ChatCompletion response + - Put that model behind a server (e.g. using WebUI) and set `OPENAI_API_BASE` ```python class LLMChatCompletionWrapper(ABC): @@ -61,18 +63,19 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper): } """ ``` +See full file [here](llm_chat_completion_wrappers/airoboros.py). --- ## Status of ChatCompletion w/ function calling and open LLMs -MemGPT uses function calling to do memory management. With OpenAI's ChatCompletion API, you can pass in a function schema in the ‘functions' keyword arg, and the API response will include a ‘function_call’ field that includes the function name and the function arguments (generated JSON). How this works under the hood is your ‘functions’ keyword is combined with the ‘messages’ and ‘system' to form one big string input to the transformer, and the output of the transformer is parsed to extract the JSON function call. +MemGPT uses function calling to do memory management. With OpenAI's ChatCompletion API, you can pass in a function schema in the `functions` keyword arg, and the API response will include a `function_call` field that includes the function name and the function arguments (generated JSON). How this works under the hood is your `functions` keyword is combined with the `messages` and `system` to form one big string input to the transformer, and the output of the transformer is parsed to extract the JSON function call. In the future, more open LLMs and LLM servers (that can host OpenAI-compatable ChatCompletion endpoints) may start including parsing code to do this automatically as standard practice. However, in the meantime, when you see a model that says it supports “function calling”, like Airoboros, it doesn't mean that you can just load Airoboros into a ChatCompletion-compatable endpoint like FastChat, and then use the same OpenAI API call and it'll just work. -(1) When an open LLM says it supports function calling, they probably mean that the model was finetuned on some function call data. Remember, transformers are just string-in-string-out, so there are many ways to format this function call data. Airoboros formats the function schema in YAML style (see https://huggingface.co/jondurbin/airoboros-l2-70b-3.1.2#agentfunction-calling)) and the output is in JSON style. To get this to work behind a ChatCompletion API, you still have to do the parsing from ‘functions’ keyword arg (containing the schema) to the model's expected schema style in the prompt (YAML for Airoboros), and you have to run some code to extract the function call (JSON for Airoboros) and package it cleanly as a ‘function_call’ field in the response. +1. When an open LLM says it supports function calling, they probably mean that the model was finetuned on some function call data. Remember, transformers are just string-in-string-out, so there are many ways to format this function call data. Airoboros formats the function schema in YAML style (see https://huggingface.co/jondurbin/airoboros-l2-70b-3.1.2#agentfunction-calling) and the output is in JSON style. To get this to work behind a ChatCompletion API, you still have to do the parsing from ‘functions’ keyword arg (containing the schema) to the model's expected schema style in the prompt (YAML for Airoboros), and you have to run some code to extract the function call (JSON for Airoboros) and package it cleanly as a ‘function_call’ field in the response. -(2) Partly because of how complex it is to support function calling, most (all?) of the community projects that do OpenAI ChatCompletion endpoints for arbitrary open LLMs do not support function calling, because if they did, they would need to write model-specific parsing code for each one. +2. Partly because of how complex it is to support function calling, most (all?) of the community projects that do OpenAI ChatCompletion endpoints for arbitrary open LLMs do not support function calling, because if they did, they would need to write model-specific parsing code for each one. ## How can you run MemGPT with open LLMs that support function calling? From f4ae08f6f5fa0cf15d874091df6769f68b9495de Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Sun, 22 Oct 2023 23:59:46 -0700 Subject: [PATCH 07/21] add comment about no inner mono + blackified the code --- memgpt/local_llm/chat_completion_proxy.py | 59 +++++++------ .../llm_chat_completion_wrappers/airoboros.py | 51 +++++++----- .../wrapper_base.py | 1 - memgpt/local_llm/webui_settings.py | 82 +++++++++---------- memgpt/openai_tools.py | 21 ++--- 5 files changed, 115 insertions(+), 99 deletions(-) diff --git a/memgpt/local_llm/chat_completion_proxy.py b/memgpt/local_llm/chat_completion_proxy.py index 39f69109..ea5b904f 100644 --- a/memgpt/local_llm/chat_completion_proxy.py +++ b/memgpt/local_llm/chat_completion_proxy.py @@ -13,8 +13,8 @@ import requests from .webui_settings import DETERMINISTIC, SIMPLE from .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 == ChatCompletion class 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 expects prompt = 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"] = prompt try: - - 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 response except Exception as e: diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py b/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py index 303e2d37..6b3a117f 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 LLMChatCompletionWrapper class 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_content self.include_assistant_prefix = include_assistant_prefix self.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 preamble def 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 type func_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 messages for 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": # TODO continue # prompt += f"\nASSISTANT: (function return) {message['content']}" @@ -107,9 +114,9 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper): cleaned_function_name = function_name cleaned_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 makes return 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 message diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/wrapper_base.py b/memgpt/local_llm/llm_chat_completion_wrappers/wrapper_base.py index d2e7584e..b1186c46 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, abstractmethod class LLMChatCompletionWrapper(ABC): - @abstractmethod def 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.py index dc578084..2601f642 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' + # '', # '<|', # '\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' + # '', # '<|', # '\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.py index 7729ae15..3d63d134 100644 --- a/memgpt/openai_tools.py +++ b/memgpt/openai_tools.py @@ -4,10 +4,12 @@ import os import time from .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 == ChatCompletion import openai + if HOST is not None: openai.api_base = HOST @@ -108,25 +110,24 @@ def aretry_with_exponential_backoff( @aretry_with_exponential_backoff async def acompletions_with_backoff(**kwargs): - # Local model if HOST_TYPE is not None: return await get_chat_completion(**kwargs) # OpenAI / Azure model else: - 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_deployment return await openai.ChatCompletion.acreate(**kwargs) @aretry_with_exponential_backoff async 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_deployment return 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 function It 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 From faaa9a04fa80c1b686b5a3afc97fa607a41af9c1 Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Mon, 23 Oct 2023 00:41:10 -0700 Subject: [PATCH 08/21] refactored + updated the airo wrapper a bit --- memgpt/local_llm/chat_completion_proxy.py | 104 +++++++----------- .../llm_chat_completion_wrappers/airoboros.py | 63 +++++++++-- memgpt/local_llm/utils.py | 8 ++ memgpt/local_llm/webui/api.py | 33 ++++++ memgpt/local_llm/webui/settings.py | 12 ++ memgpt/local_llm/webui_settings.py | 54 --------- 6 files changed, 150 insertions(+), 124 deletions(-) create mode 100644 memgpt/local_llm/utils.py create mode 100644 memgpt/local_llm/webui/api.py create mode 100644 memgpt/local_llm/webui/settings.py delete mode 100644 memgpt/local_llm/webui_settings.py diff --git a/memgpt/local_llm/chat_completion_proxy.py b/memgpt/local_llm/chat_completion_proxy.py index ea5b904f..ae983339 100644 --- a/memgpt/local_llm/chat_completion_proxy.py +++ b/memgpt/local_llm/chat_completion_proxy.py @@ -1,30 +1,16 @@ -"""MemGPT sends a ChatCompletion request - -Under the hood, we use the functions argument to turn -""" - - """Key idea: create drop-in replacement for agent's ChatCompletion call that runs on an OpenLLM backend""" import os -import json import requests +import json -from .webui_settings import DETERMINISTIC, SIMPLE +from .webui.api import get_webui_completion from .llm_chat_completion_wrappers import airoboros +from .utils import DotDict HOST = os.getenv("OPENAI_API_BASE") HOST_TYPE = os.getenv("BACKEND_TYPE") # default None == ChatCompletion - - -class DotDict(dict): - """Allow dot access on properties similar to OpenAI response object""" - - def __getattr__(self, attr): - return self.get(attr) - - def __setattr__(self, key, value): - self[key] = value +DEBUG = True async def get_chat_completion( @@ -36,60 +22,52 @@ async def get_chat_completion( if function_call != "auto": raise ValueError(f"function_call == {function_call} not supported (auto only)") - if True or model == "airoboros_v2.1": + if model == "airoboros_v2.1": + llm_wrapper = airoboros.Airoboros21Wrapper() + else: + # Warn the user that we're using the fallback + print( + f"Warning: could not find an LLM wrapper for {model}, using the airoboros wrapper" + ) llm_wrapper = airoboros.Airoboros21Wrapper() # First step: turn the message sequence into a prompt that the model expects prompt = llm_wrapper.chat_completion_to_prompt(messages, functions) - # print(prompt) - - if HOST_TYPE != "webui": - raise ValueError(HOST_TYPE) - - request = SIMPLE - request["prompt"] = prompt + if DEBUG: + print(prompt) try: - 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"] - print(f"json API response.text: {result}") + if HOST_TYPE == "webui": + result = get_webui_completion(prompt) else: - raise Exception(f"API call got non-200 response code") + raise ValueError(HOST_TYPE) + except requests.exceptions.ConnectionError as e: + raise ValueError(f"Was unable to connect to host {HOST}") - # cleaned_result, chatcompletion_result = parse_st_json_output(result) - chat_completion_result = llm_wrapper.output_to_chat_completion_response(result) + chat_completion_result = llm_wrapper.output_to_chat_completion_response(result) + if DEBUG: print(json.dumps(chat_completion_result, indent=2)) - # 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( + # unpack with response.choices[0].message.content + response = DotDict( + { + "model": None, + "choices": [ + DotDict( { - # TODO fix - "prompt_tokens": 0, - "completion_tokens": 0, - "total_tokens": 0, + "message": DotDict(chat_completion_result), + "finish_reason": "stop", # TODO vary based on backend response } - ), - } - ) - return response - - except Exception as e: - # TODO - raise e + ) + ], + "usage": DotDict( + { + # TODO fix, actually use real info + "prompt_tokens": 0, + "completion_tokens": 0, + "total_tokens": 0, + } + ), + } + ) + return response diff --git a/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py b/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py index 6b3a117f..98d3625e 100644 --- a/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py +++ b/memgpt/local_llm/llm_chat_completion_wrappers/airoboros.py @@ -12,12 +12,16 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper): def __init__( self, simplify_json_content=True, - include_assistant_prefix=True, clean_function_args=True, + include_assistant_prefix=True, + include_opening_brace_in_prefix=True, + include_section_separators=True, ): self.simplify_json_content = simplify_json_content - self.include_assistant_prefix = include_assistant_prefix self.clean_func_args = clean_function_args + self.include_assistant_prefix = include_assistant_prefix + self.include_opening_brance_in_prefix = include_opening_brace_in_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 @@ -77,11 +81,41 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper): # TODO we're ignoring schema['parameters']['required'] return func_str - prompt += f"\nPlease 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." + # prompt += f"\nPlease 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." + prompt += f"\nPlease select the most suitable function and parameters from the list of available functions below, based on the ongoing conversation. Provide your response in JSON format." prompt += f"\nAvailable functions:" for function_dict in functions: prompt += f"\n{create_function_description(function_dict)}" + 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 @@ -96,16 +130,25 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper): 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 - continue + # 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" + if self.include_assistant_prefix: - # prompt += f"\nPlease 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." prompt += f"\nASSISTANT:" + if self.include_opening_brance_in_prefix: + prompt += "\n{" return prompt @@ -135,7 +178,13 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper): } } """ - function_json_output = json.loads(raw_llm_output) + if self.include_opening_brance_in_prefix and raw_llm_output[0] != "{": + raw_llm_output = "{" + raw_llm_output + + try: + 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"] diff --git a/memgpt/local_llm/utils.py b/memgpt/local_llm/utils.py new file mode 100644 index 00000000..42a0ce27 --- /dev/null +++ b/memgpt/local_llm/utils.py @@ -0,0 +1,8 @@ +class DotDict(dict): + """Allow dot access on properties similar to OpenAI response object""" + + def __getattr__(self, attr): + return self.get(attr) + + def __setattr__(self, key, value): + self[key] = value diff --git a/memgpt/local_llm/webui/api.py b/memgpt/local_llm/webui/api.py new file mode 100644 index 00000000..3cff08e0 --- /dev/null +++ b/memgpt/local_llm/webui/api.py @@ -0,0 +1,33 @@ +import os +import requests + +from .settings import SIMPLE + +HOST = os.getenv("OPENAI_API_BASE") +HOST_TYPE = os.getenv("BACKEND_TYPE") # default None == ChatCompletion +WEBUI_API_SUFFIX = "/v1/generate" +DEBUG = True + + +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""" + + # Settings for the generation, includes the prompt + stop tokens, max length, etc + request = settings + request["prompt"] = prompt + + try: + URI = f"{HOST}{WEBUI_API_SUFFIX}" + response = requests.post(URI, json=request) + if response.status_code == 200: + result = response.json() + result = result["results"][0]["text"] + if DEBUG: + print(f"json API response.text: {result}") + else: + raise Exception(f"API call got non-200 response code") + except: + # TODO handle gracefully + raise + + return result diff --git a/memgpt/local_llm/webui/settings.py b/memgpt/local_llm/webui/settings.py new file mode 100644 index 00000000..2e9ecbce --- /dev/null +++ b/memgpt/local_llm/webui/settings.py @@ -0,0 +1,12 @@ +SIMPLE = { + "stopping_strings": [ + "\nUSER:", + "\nASSISTANT:", + # '\n' + + # '', + # '<|', + # '\n#', + # '\n\n\n', + ], + "truncation_length": 4096, # assuming llama2 models +} diff --git a/memgpt/local_llm/webui_settings.py b/memgpt/local_llm/webui_settings.py deleted file mode 100644 index 2601f642..00000000 --- a/memgpt/local_llm/webui_settings.py +++ /dev/null @@ -1,54 +0,0 @@ -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:", - # '\n' + - # '', - # '<|', - # '\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, -} - -SIMPLE = { - "stopping_strings": [ - "\nUSER:", - "\nASSISTANT:", - # '\n' + - # '', - # '<|', - # '\n#', - # '\n\n\n', - ], - "truncation_length": 4096, -} From 3d2b4c74891c078461e38cf8fa099a9015c70b90 Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Mon, 23 Oct 2023 00:43:47 -0700 Subject: [PATCH 09/21] default to webui if BACKEND_TYPE is not set --- memgpt/local_llm/chat_completion_proxy.py | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/memgpt/local_llm/chat_completion_proxy.py b/memgpt/local_llm/chat_completion_proxy.py index ae983339..f4fe7b81 100644 --- a/memgpt/local_llm/chat_completion_proxy.py +++ b/memgpt/local_llm/chat_completion_proxy.py @@ -40,7 +40,8 @@ async def get_chat_completion( if HOST_TYPE == "webui": result = get_webui_completion(prompt) else: - raise ValueError(HOST_TYPE) + print(f"Warning: HOST_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}") From a49731d71439bf63b3347396649fe71bdf7b0c6d Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Mon, 23 Oct 2023 00:44:43 -0700 Subject: [PATCH 10/21] typo --- memgpt/local_llm/chat_completion_proxy.py | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/memgpt/local_llm/chat_completion_proxy.py b/memgpt/local_llm/chat_completion_proxy.py index f4fe7b81..a5290717 100644 --- a/memgpt/local_llm/chat_completion_proxy.py +++ b/memgpt/local_llm/chat_completion_proxy.py @@ -40,7 +40,7 @@ async def get_chat_completion( if HOST_TYPE == "webui": result = get_webui_completion(prompt) else: - print(f"Warning: HOST_TYPE was not set, defaulting to webui") + 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}") From ed52ea6aafe4d16d810268edc69e8e3b7cc2a8ad Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Mon, 23 Oct 2023 00:56:02 -0700 Subject: [PATCH 11/21] Update README.md --- memgpt/local_llm/README.md | 27 +++++++++++---------------- 1 file changed, 11 insertions(+), 16 deletions(-) diff --git a/memgpt/local_llm/README.md b/memgpt/local_llm/README.md index 69165305..7f54b9a2 100644 --- a/memgpt/local_llm/README.md +++ b/memgpt/local_llm/README.md @@ -1,19 +1,14 @@ -## How to connect MemGPT to non-OpenAI LLMs +⁉️ Need help configuring local LLMs with MemGPT? Ask for help on [our Discord](https://discord.gg/9GEQrxmVyE) or [post on the GitHub discussion](https://github.com/cpacker/MemGPT/discussions/67). -**If you have a hosted ChatCompletion-compatible endpoint that works with function calling**: - - simply set `OPENAI_API_BASE` to the IP+port of your endpoint: +👀 If you have a hosted ChatCompletion-compatible endpoint that works with function calling, you can simply set `OPENAI_API_BASE` (`export OPENAI_API_BASE=...`) to the IP+port of your endpoint. **As of 10/22/2023, most ChatCompletion endpoints do *NOT* support function calls, so if you want to play with MemGPT and open models, you probably need to follow the instructions below.** -```sh -export OPENAI_API_BASE=... -``` +🙋 Our examples assume that you're using [oobabooga web UI](https://github.com/oobabooga/text-generation-webui#starting-the-web-ui) to put your LLMs behind a web server. If you need help setting this up, check the instructions [here](https://github.com/oobabooga/text-generation-webui#starting-the-web-ui). More LLM web server support to come soon (tell us what you use and we'll add it)! -For this to work, the endpoint **MUST** support function calls. +--- -**As of 10/22/2023, most ChatCompletion endpoints do *NOT* support function calls, so if you want to play with MemGPT and open models, you probably need to follow the instructions below.** +# How to connect MemGPT to non-OpenAI LLMs -## Integrating a function-call finetuned LLM with MemGPT - -**If you have a hosted local model that is function-call finetuned**: +**If you have an LLM that is function-call finetuned**: - Implement a wrapper class for that model - The wrapper class needs to implement two functions: - One to go from ChatCompletion messages/functions schema to a prompt string @@ -34,9 +29,9 @@ class LLMChatCompletionWrapper(ABC): pass ``` -## Example with Airoboros LLM +## Example with [Airoboros](https://huggingface.co/jondurbin/airoboros-l2-70b-2.1) (llama2 finetune) -To help you get started, we've implemented an example wrapper class for a popular llama2 model finetuned on function calling (airoboros). We want MemGPT to run well on open models as much as you do, so we'll be actively updating this page with more examples. Additionally, we welcome contributions from the community! If you find an open LLM that works well with MemGPT, please open a PR with a model wrapper and we'll merge it ASAP. +To help you get started, we've implemented an example wrapper class for a popular llama2 model **finetuned on function calling** (airoboros). We want MemGPT to run well on open models as much as you do, so we'll be actively updating this page with more examples. Additionally, we welcome contributions from the community! If you find an open LLM that works well with MemGPT, please open a PR with a model wrapper and we'll merge it ASAP. ```python class Airoboros21Wrapper(LLMChatCompletionWrapper): @@ -77,8 +72,8 @@ In the future, more open LLMs and LLM servers (that can host OpenAI-compatable C 2. Partly because of how complex it is to support function calling, most (all?) of the community projects that do OpenAI ChatCompletion endpoints for arbitrary open LLMs do not support function calling, because if they did, they would need to write model-specific parsing code for each one. -## How can you run MemGPT with open LLMs that support function calling? +## What is this all this extra code for? -Because of the poor state of function calling support in existing ChatCompletion API serving code, we instead provide a light wrapper on top of ChatCompletion that uses a parser specific to Airoboros. We hope that this example code will help the community add additional compatability of MemGPT with more function-calling LLMs - we will also add more model support as we test more models and find those that work well enough to run MemGPT's function set. +Because of the poor state of function calling support in existing ChatCompletion API serving code, we instead provide a light wrapper on top of ChatCompletion that add parsers to handle function calling support. These parsers need to be specific to the model you're using (or at least specific to the way it was trained on function calling). We hope that our example code will help the community add additional compatability of MemGPT with more function-calling LLMs - we will also add more model support as we test more models and find those that work well enough to run MemGPT's function set. -To run the example of MemGPT with Airoboros, you'll need to host the model with some open LLM hosting code, for example Oobagooba (see here). Then, all you need to do is point MemGPT to this API endpoint. Now, instead of calling ChatCompletion on OpenAI's API, MemGPT will use it's own ChatCompletion wrapper that parses the system, messages, and function arguments into a format that Airoboros has been finetuned on, and once Airoboros generates a string output, MemGPT will parse the response to extract a potential function call (knowing what we know about Airoboros expected function call output). +To run the example of MemGPT with Airoboros, you'll need to host the model behind some LLM web server (for example [webui](https://github.com/oobabooga/text-generation-webui#starting-the-web-ui)). Then, all you need to do is point MemGPT to this API endpoint by setting `OPENAI_API_BASE` and `BACKEND_TYPE`. Now, instead of calling ChatCompletion on OpenAI's API, MemGPT will use it's own ChatCompletion wrapper that parses the system, messages, and function arguments into a format that Airoboros has been finetuned on, and once Airoboros generates a string output, MemGPT will parse the response to extract a potential function call (knowing what we know about Airoboros expected function call output). From 0478a7a49ed8687026be56ea98fe0842ff22877e Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Mon, 23 Oct 2023 00:57:37 -0700 Subject: [PATCH 12/21] Update README.md --- memgpt/local_llm/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/memgpt/local_llm/README.md b/memgpt/local_llm/README.md index 7f54b9a2..fce5899b 100644 --- a/memgpt/local_llm/README.md +++ b/memgpt/local_llm/README.md @@ -68,7 +68,7 @@ MemGPT uses function calling to do memory management. With OpenAI's ChatCompleti In the future, more open LLMs and LLM servers (that can host OpenAI-compatable ChatCompletion endpoints) may start including parsing code to do this automatically as standard practice. However, in the meantime, when you see a model that says it supports “function calling”, like Airoboros, it doesn't mean that you can just load Airoboros into a ChatCompletion-compatable endpoint like FastChat, and then use the same OpenAI API call and it'll just work. -1. When an open LLM says it supports function calling, they probably mean that the model was finetuned on some function call data. Remember, transformers are just string-in-string-out, so there are many ways to format this function call data. Airoboros formats the function schema in YAML style (see https://huggingface.co/jondurbin/airoboros-l2-70b-3.1.2#agentfunction-calling) and the output is in JSON style. To get this to work behind a ChatCompletion API, you still have to do the parsing from ‘functions’ keyword arg (containing the schema) to the model's expected schema style in the prompt (YAML for Airoboros), and you have to run some code to extract the function call (JSON for Airoboros) and package it cleanly as a ‘function_call’ field in the response. +1. When a model page says it supports function calling, they probably mean that the model was finetuned on some function call data (not that you can just use ChatCompletion with functions out-of-the-box). Remember, LLMs are just string-in-string-out, so there are many ways to format the function call data. E.g. Airoboros formats the function schema in YAML style (see https://huggingface.co/jondurbin/airoboros-l2-70b-3.1.2#agentfunction-calling) and the output is in JSON style. To get this to work behind a ChatCompletion API, you still have to do the parsing from ‘functions’ keyword arg (containing the schema) to the model's expected schema style in the prompt (YAML for Airoboros), and you have to run some code to extract the function call (JSON for Airoboros) and package it cleanly as a ‘function_call’ field in the response. 2. Partly because of how complex it is to support function calling, most (all?) of the community projects that do OpenAI ChatCompletion endpoints for arbitrary open LLMs do not support function calling, because if they did, they would need to write model-specific parsing code for each one. From ab1f75a368c26e253f26e05267c43e0c62bc7939 Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Mon, 23 Oct 2023 01:01:41 -0700 Subject: [PATCH 13/21] Update README.md --- memgpt/local_llm/README.md | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/memgpt/local_llm/README.md b/memgpt/local_llm/README.md index fce5899b..a62bfe24 100644 --- a/memgpt/local_llm/README.md +++ b/memgpt/local_llm/README.md @@ -60,6 +60,30 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper): ``` See full file [here](llm_chat_completion_wrappers/airoboros.py). +Example running the code (airoboros is able to properly call `send_message`: +```sh +# running airoboros behind a textgen webui server +export OPENAI_API_BASE = +export BACKEND_TYPE = webui + +# using --no_verify because this airoboros example does not output inner monologue, just functions +$ python3 main.py --no_verify + +Running... [exit by typing '/exit'] +💭 Bootup sequence complete. Persona activated. Testing messaging functionality. + +💭 None +🤖 Welcome! My name is Sam. How can I assist you today? +Enter your message: My name is Brad, not Chad... + +💭 None +⚡🧠 [function] updating memory with core_memory_replace: + First name: Chad + → First name: Brad +``` + +WebUI exposes a lot of parameters that can dramatically change LLM outputs, to change these you can modify the [WebUI settings file](/memgpt/local_llm/webui/settings.py). + --- ## Status of ChatCompletion w/ function calling and open LLMs From 34f5a74f62b051fd468595430add1f725845771e Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Mon, 23 Oct 2023 01:02:25 -0700 Subject: [PATCH 14/21] Update README.md --- memgpt/local_llm/README.md | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/memgpt/local_llm/README.md b/memgpt/local_llm/README.md index a62bfe24..60ca74be 100644 --- a/memgpt/local_llm/README.md +++ b/memgpt/local_llm/README.md @@ -60,13 +60,15 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper): ``` See full file [here](llm_chat_completion_wrappers/airoboros.py). -Example running the code (airoboros is able to properly call `send_message`: +### Running the example + ```sh # running airoboros behind a textgen webui server export OPENAI_API_BASE = export BACKEND_TYPE = webui # using --no_verify because this airoboros example does not output inner monologue, just functions +# airoboros is able to properly call `send_message` $ python3 main.py --no_verify Running... [exit by typing '/exit'] From d8c0092a3eb4afd13c50cb38400106a1e0c93716 Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Mon, 23 Oct 2023 01:02:40 -0700 Subject: [PATCH 15/21] Update README.md --- memgpt/local_llm/README.md | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/memgpt/local_llm/README.md b/memgpt/local_llm/README.md index 60ca74be..5bbe2162 100644 --- a/memgpt/local_llm/README.md +++ b/memgpt/local_llm/README.md @@ -58,7 +58,7 @@ class Airoboros21Wrapper(LLMChatCompletionWrapper): } """ ``` -See full file [here](llm_chat_completion_wrappers/airoboros.py). +See full file [here](llm_chat_completion_wrappers/airoboros.py). WebUI exposes a lot of parameters that can dramatically change LLM outputs, to change these you can modify the [WebUI settings file](/memgpt/local_llm/webui/settings.py). ### Running the example @@ -84,8 +84,6 @@ Enter your message: My name is Brad, not Chad... → First name: Brad ``` -WebUI exposes a lot of parameters that can dramatically change LLM outputs, to change these you can modify the [WebUI settings file](/memgpt/local_llm/webui/settings.py). - --- ## Status of ChatCompletion w/ function calling and open LLMs From a2b824ecb538f25f5429b3d27a314580e803dfe0 Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Mon, 23 Oct 2023 01:04:02 -0700 Subject: [PATCH 16/21] Update README.md --- memgpt/local_llm/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/memgpt/local_llm/README.md b/memgpt/local_llm/README.md index 5bbe2162..001d4a58 100644 --- a/memgpt/local_llm/README.md +++ b/memgpt/local_llm/README.md @@ -88,7 +88,7 @@ Enter your message: My name is Brad, not Chad... ## Status of ChatCompletion w/ function calling and open LLMs -MemGPT uses function calling to do memory management. With OpenAI's ChatCompletion API, you can pass in a function schema in the `functions` keyword arg, and the API response will include a `function_call` field that includes the function name and the function arguments (generated JSON). How this works under the hood is your `functions` keyword is combined with the `messages` and `system` to form one big string input to the transformer, and the output of the transformer is parsed to extract the JSON function call. +MemGPT uses function calling to do memory management. With [OpenAI's ChatCompletion API](https://platform.openai.com/docs/api-reference/chat/), you can pass in a function schema in the `functions` keyword arg, and the API response will include a `function_call` field that includes the function name and the function arguments (generated JSON). How this works under the hood is your `functions` keyword is combined with the `messages` and `system` to form one big string input to the transformer, and the output of the transformer is parsed to extract the JSON function call. In the future, more open LLMs and LLM servers (that can host OpenAI-compatable ChatCompletion endpoints) may start including parsing code to do this automatically as standard practice. However, in the meantime, when you see a model that says it supports “function calling”, like Airoboros, it doesn't mean that you can just load Airoboros into a ChatCompletion-compatable endpoint like FastChat, and then use the same OpenAI API call and it'll just work. From 489981240c3bd0fa0413adc3781778f1ba212916 Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Mon, 23 Oct 2023 01:04:45 -0700 Subject: [PATCH 17/21] Update README.md --- memgpt/local_llm/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/memgpt/local_llm/README.md b/memgpt/local_llm/README.md index 001d4a58..e5c91950 100644 --- a/memgpt/local_llm/README.md +++ b/memgpt/local_llm/README.md @@ -90,7 +90,7 @@ Enter your message: My name is Brad, not Chad... MemGPT uses function calling to do memory management. With [OpenAI's ChatCompletion API](https://platform.openai.com/docs/api-reference/chat/), you can pass in a function schema in the `functions` keyword arg, and the API response will include a `function_call` field that includes the function name and the function arguments (generated JSON). How this works under the hood is your `functions` keyword is combined with the `messages` and `system` to form one big string input to the transformer, and the output of the transformer is parsed to extract the JSON function call. -In the future, more open LLMs and LLM servers (that can host OpenAI-compatable ChatCompletion endpoints) may start including parsing code to do this automatically as standard practice. However, in the meantime, when you see a model that says it supports “function calling”, like Airoboros, it doesn't mean that you can just load Airoboros into a ChatCompletion-compatable endpoint like FastChat, and then use the same OpenAI API call and it'll just work. +In the future, more open LLMs and LLM servers (that can host OpenAI-compatable ChatCompletion endpoints) may start including parsing code to do this automatically as standard practice. However, in the meantime, when you see a model that says it supports “function calling”, like Airoboros, it doesn't mean that you can just load Airoboros into a ChatCompletion-compatable endpoint like WebUI, and then use the same OpenAI API call and it'll just work. 1. When a model page says it supports function calling, they probably mean that the model was finetuned on some function call data (not that you can just use ChatCompletion with functions out-of-the-box). Remember, LLMs are just string-in-string-out, so there are many ways to format the function call data. E.g. Airoboros formats the function schema in YAML style (see https://huggingface.co/jondurbin/airoboros-l2-70b-3.1.2#agentfunction-calling) and the output is in JSON style. To get this to work behind a ChatCompletion API, you still have to do the parsing from ‘functions’ keyword arg (containing the schema) to the model's expected schema style in the prompt (YAML for Airoboros), and you have to run some code to extract the function call (JSON for Airoboros) and package it cleanly as a ‘function_call’ field in the response. From 33551b1106d9d6effa895f287c9e14f24dbd9255 Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Mon, 23 Oct 2023 01:05:22 -0700 Subject: [PATCH 18/21] Update README.md --- memgpt/local_llm/README.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/memgpt/local_llm/README.md b/memgpt/local_llm/README.md index e5c91950..f45c16c4 100644 --- a/memgpt/local_llm/README.md +++ b/memgpt/local_llm/README.md @@ -92,7 +92,7 @@ MemGPT uses function calling to do memory management. With [OpenAI's ChatComplet In the future, more open LLMs and LLM servers (that can host OpenAI-compatable ChatCompletion endpoints) may start including parsing code to do this automatically as standard practice. However, in the meantime, when you see a model that says it supports “function calling”, like Airoboros, it doesn't mean that you can just load Airoboros into a ChatCompletion-compatable endpoint like WebUI, and then use the same OpenAI API call and it'll just work. -1. When a model page says it supports function calling, they probably mean that the model was finetuned on some function call data (not that you can just use ChatCompletion with functions out-of-the-box). Remember, LLMs are just string-in-string-out, so there are many ways to format the function call data. E.g. Airoboros formats the function schema in YAML style (see https://huggingface.co/jondurbin/airoboros-l2-70b-3.1.2#agentfunction-calling) and the output is in JSON style. To get this to work behind a ChatCompletion API, you still have to do the parsing from ‘functions’ keyword arg (containing the schema) to the model's expected schema style in the prompt (YAML for Airoboros), and you have to run some code to extract the function call (JSON for Airoboros) and package it cleanly as a ‘function_call’ field in the response. +1. When a model page says it supports function calling, they probably mean that the model was finetuned on some function call data (not that you can just use ChatCompletion with functions out-of-the-box). Remember, LLMs are just string-in-string-out, so there are many ways to format the function call data. E.g. Airoboros formats the function schema in YAML style (see https://huggingface.co/jondurbin/airoboros-l2-70b-3.1.2#agentfunction-calling) and the output is in JSON style. To get this to work behind a ChatCompletion API, you still have to do the parsing from `functions` keyword arg (containing the schema) to the model's expected schema style in the prompt (YAML for Airoboros), and you have to run some code to extract the function call (JSON for Airoboros) and package it cleanly as a `function_call` field in the response. 2. Partly because of how complex it is to support function calling, most (all?) of the community projects that do OpenAI ChatCompletion endpoints for arbitrary open LLMs do not support function calling, because if they did, they would need to write model-specific parsing code for each one. From 7721cad39257af122d52e3b66b72e968f10d27db Mon Sep 17 00:00:00 2001 From: Vivian Fang Date: Mon, 23 Oct 2023 01:07:13 -0700 Subject: [PATCH 19/21] Update README.md --- memgpt/local_llm/README.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/memgpt/local_llm/README.md b/memgpt/local_llm/README.md index f45c16c4..a79c0f9e 100644 --- a/memgpt/local_llm/README.md +++ b/memgpt/local_llm/README.md @@ -31,7 +31,7 @@ class LLMChatCompletionWrapper(ABC): ## Example with [Airoboros](https://huggingface.co/jondurbin/airoboros-l2-70b-2.1) (llama2 finetune) -To help you get started, we've implemented an example wrapper class for a popular llama2 model **finetuned on function calling** (airoboros). We want MemGPT to run well on open models as much as you do, so we'll be actively updating this page with more examples. Additionally, we welcome contributions from the community! If you find an open LLM that works well with MemGPT, please open a PR with a model wrapper and we'll merge it ASAP. +To help you get started, we've implemented an example wrapper class for a popular llama2 model **finetuned on function calling** (Airoboros). We want MemGPT to run well on open models as much as you do, so we'll be actively updating this page with more examples. Additionally, we welcome contributions from the community! If you find an open LLM that works well with MemGPT, please open a PR with a model wrapper and we'll merge it ASAP. ```python class Airoboros21Wrapper(LLMChatCompletionWrapper): @@ -98,6 +98,6 @@ In the future, more open LLMs and LLM servers (that can host OpenAI-compatable C ## What is this all this extra code for? -Because of the poor state of function calling support in existing ChatCompletion API serving code, we instead provide a light wrapper on top of ChatCompletion that add parsers to handle function calling support. These parsers need to be specific to the model you're using (or at least specific to the way it was trained on function calling). We hope that our example code will help the community add additional compatability of MemGPT with more function-calling LLMs - we will also add more model support as we test more models and find those that work well enough to run MemGPT's function set. +Because of the poor state of function calling support in existing ChatCompletion API serving code, we instead provide a light wrapper on top of ChatCompletion that adds parsers to handle function calling support. These parsers need to be specific to the model you're using (or at least specific to the way it was trained on function calling). We hope that our example code will help the community add additional compatability of MemGPT with more function-calling LLMs - we will also add more model support as we test more models and find those that work well enough to run MemGPT's function set. -To run the example of MemGPT with Airoboros, you'll need to host the model behind some LLM web server (for example [webui](https://github.com/oobabooga/text-generation-webui#starting-the-web-ui)). Then, all you need to do is point MemGPT to this API endpoint by setting `OPENAI_API_BASE` and `BACKEND_TYPE`. Now, instead of calling ChatCompletion on OpenAI's API, MemGPT will use it's own ChatCompletion wrapper that parses the system, messages, and function arguments into a format that Airoboros has been finetuned on, and once Airoboros generates a string output, MemGPT will parse the response to extract a potential function call (knowing what we know about Airoboros expected function call output). +To run the example of MemGPT with Airoboros, you'll need to host the model behind some LLM web server (for example [webui](https://github.com/oobabooga/text-generation-webui#starting-the-web-ui)). Then, all you need to do is point MemGPT to this API endpoint by setting the environment variables `OPENAI_API_BASE` and `BACKEND_TYPE`. Now, instead of calling ChatCompletion on OpenAI's API, MemGPT will use it's own ChatCompletion wrapper that parses the system, messages, and function arguments into a format that Airoboros has been finetuned on, and once Airoboros generates a string output, MemGPT will parse the response to extract a potential function call (knowing what we know about Airoboros expected function call output). From cbbe8a3ce6844ace409b1c4ad35dca4485a462f2 Mon Sep 17 00:00:00 2001 From: Vivian Fang Date: Mon, 23 Oct 2023 01:09:44 -0700 Subject: [PATCH 20/21] Update README.md --- README.md | 3 +++ 1 file changed, 3 insertions(+) diff --git a/README.md b/README.md index 347dc39f..f85e8d72 100644 --- a/README.md +++ b/README.md @@ -130,6 +130,9 @@ python main.py --model gpt-3.5-turbo Please report any bugs you encounter regarding MemGPT running on GPT-3.5 to https://github.com/cpacker/MemGPT/issues/59. +### Local LLM support +You can run MemGPT with local LLMs too. See [instructions here](/memgpt/local_llm) and report any bugs/improvements here https://github.com/cpacker/MemGPT/discussions/67. + ### `main.py` flags ```text From 326bdb10a91fa3fae2a3e44326dd78f5e0ec8d2c Mon Sep 17 00:00:00 2001 From: Charles Packer Date: Mon, 23 Oct 2023 01:13:02 -0700 Subject: [PATCH 21/21] Update README.md --- README.md | 2 ++ 1 file changed, 2 insertions(+) diff --git a/README.md b/README.md index f85e8d72..2362d4e8 100644 --- a/README.md +++ b/README.md @@ -5,6 +5,8 @@
Try out our MemGPT chatbot on Discord! + + ⭐ NEW: You can now run MemGPT with local LLMs! ⭐ [![Discord](https://img.shields.io/discord/1161736243340640419?label=Discord&logo=discord&logoColor=5865F2&style=flat-square&color=5865F2)](https://discord.gg/9GEQrxmVyE) [![arXiv 2310.08560](https://img.shields.io/badge/arXiv-2310.08560-B31B1B?logo=arxiv&style=flat-square)](https://arxiv.org/abs/2310.08560)