├── .gitignore ├── chatstack ├── __init__.py ├── pricing.py ├── retry.py └── chatstack.py ├── pyproject.toml ├── example ├── basic.py ├── stream.py └── context.py ├── README.md └── LICENSE /.gitignore: -------------------------------------------------------------------------------- 1 | *.pyc 2 | *.hnsw 3 | *~ 4 | chatstack.egg-info/* 5 | dist/* 6 | build/* -------------------------------------------------------------------------------- /chatstack/__init__.py: -------------------------------------------------------------------------------- 1 | 2 | from .chatstack import SystemMessage, ContextMessage, UserMessage, ChatRoleMessage, AssistantMessage, ChatContext 3 | -------------------------------------------------------------------------------- /chatstack/pricing.py: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | def price(model, input_tokens, output_tokens): 5 | # https://openai.com/pricing 6 | if model in ['gpt-3.5-turbo', 'gpt-3.5']: 7 | tokens = input_tokens + output_tokens 8 | dollars = 0.002 * tokens / 1000 9 | elif model == 'gpt-4': 10 | dollars = (.03*input_tokens + .06*output_tokens) / 1000 11 | elif model == 'gpt-4-1106-preview': 12 | dollars = (.01*input_tokens + .03*output_tokens) / 1000 13 | else: 14 | raise ValueError(f"model {model} not supported") 15 | return dollars 16 | -------------------------------------------------------------------------------- /pyproject.toml: -------------------------------------------------------------------------------- 1 | [build-system] 2 | requires = ["setuptools>=61.0"] 3 | build-backend = "setuptools.build_meta" 4 | 5 | [project] 6 | name = "chatstack" 7 | version = "0.1.5" 8 | authors = [ 9 | { name="Bill Kish", email="bk@jiggy.ai" }, 10 | ] 11 | dependencies=['pydantic', 'openai', 'tiktoken', 'loguru'] 12 | description = "Message-based LLM tools." 13 | readme = "README.md" 14 | requires-python = ">=3.7" 15 | classifiers = [ 16 | "Programming Language :: Python :: 3", 17 | "License :: OSI Approved :: Apache Software License", 18 | "Operating System :: OS Independent", 19 | ] 20 | 21 | [project.urls] 22 | "Homepage" = "https://github.com/jiggy-ai/chatstack" 23 | "Bug Tracker" = "https://github.com/jiggy-ai/chatstack/issues" -------------------------------------------------------------------------------- /example/basic.py: -------------------------------------------------------------------------------- 1 | from chatstack import ChatContext 2 | 3 | BASE_SYSTEM_PROMPT = "You are a clever bot. Do not apologize, or make excuses. " 4 | BASE_SYSTEM_PROMPT += "Do not mention that you are an AI language model since that is annoying to users." 5 | 6 | def main(): 7 | chat_context = ChatContext(base_system_msg_text=BASE_SYSTEM_PROMPT) 8 | 9 | print("Welcome to the Chatbot!") 10 | 11 | while True: 12 | user_input = input("You: ") 13 | print("Chatbot:") 14 | response = chat_context.user_message(user_input) 15 | print(response.text) 16 | # print token usage and price 17 | print(f"({response.input_tokens + response.response_tokens} tokens (${response.price:.4f}))") 18 | if __name__ == "__main__": 19 | main() 20 | -------------------------------------------------------------------------------- /example/stream.py: -------------------------------------------------------------------------------- 1 | from chatstack import ChatContext 2 | import sys 3 | 4 | BASE_SYSTEM_PROMPT = "You are a clever bot. Do not apologize, or make excuses. " 5 | BASE_SYSTEM_PROMPT += "Do not mention that you are an AI language model since that is annoying to users." 6 | 7 | def main(): 8 | chat_context = ChatContext(base_system_msg_text=BASE_SYSTEM_PROMPT) 9 | 10 | print("Welcome to the Chatbot!") 11 | 12 | while True: 13 | user_input = input("You: ") 14 | print("Chatbot:") 15 | for chat_rsp in chat_context.user_message_stream(user_input): 16 | sys.stdout.write(chat_rsp.delta) 17 | sys.stdout.flush() 18 | # print token usage and price 19 | print(f"({chat_rsp.input_tokens + chat_rsp.response_tokens} tokens (${chat_rsp.price:.4f}))") 20 | 21 | if __name__ == "__main__": 22 | main() 23 | -------------------------------------------------------------------------------- /example/context.py: -------------------------------------------------------------------------------- 1 | from chatstack import ChatContext, ContextMessage, AssistantMessage 2 | import sys 3 | from random import randint 4 | 5 | BASE_SYSTEM_PROMPT = "You are a clever bot. Do not apologize, or make excuses. " 6 | BASE_SYSTEM_PROMPT += "Help the user count the context messages. The number of context messages changes every time." 7 | 8 | def main(): 9 | chat_context = ChatContext(base_system_msg_text=BASE_SYSTEM_PROMPT) 10 | 11 | print("Welcome to the Chatbot! ") 12 | 13 | # add a context message 14 | 15 | 16 | while True: 17 | dc = [ContextMessage(text=f"context message {i}", prefix="context message") for i in range(randint(200, 400))] 18 | print(f"generated {len(dc)} context messages and added them to the context. Ask the bot about them.") 19 | user_input = input("You: ") 20 | print("Chatbot:") 21 | chat_rsp = chat_context.user_message(user_input, dynamic_context=dc) 22 | print("Chatbot: ", chat_rsp.text) 23 | user_messages = len([m for m in chat_rsp.inputs if m.role == 'user']) 24 | context_messages = len([m for m in chat_rsp.inputs if isinstance(m, ContextMessage)]) 25 | assistant_messages = len([m for m in chat_rsp.inputs if isinstance(m, AssistantMessage)]) 26 | print(f"({user_messages} user messages, {context_messages} context messages, {assistant_messages} assistant messages") 27 | # print token usage and price 28 | print(f"({chat_rsp.input_tokens + chat_rsp.response_tokens} tokens (${chat_rsp.price:.4f}))") 29 | 30 | if __name__ == "__main__": 31 | main() 32 | -------------------------------------------------------------------------------- /chatstack/retry.py: -------------------------------------------------------------------------------- 1 | """ 2 | retry decorator in a wsk style 3 | """ 4 | from loguru import logger 5 | from time import sleep 6 | from functools import wraps 7 | 8 | def retry(ExceptionToCheck=Exception, tries=5, delay=0.5, backoff=2, ExceptionToRaise=AssertionError): 9 | """Retry calling the decorated function using an exponential backoff. 10 | 11 | http://www.saltycrane.com/blog/2009/11/trying-out-retry-decorator-python/ 12 | original from: http://wiki.python.org/moin/PythonDecoratorLibrary#Retry 13 | 14 | :param ExceptionToCheck: the exception to check. may be a tuple of 15 | exceptions to check 16 | :type ExceptionToCheck: Exception or tuple 17 | :param tries: number of times to try (not retry) before giving up 18 | :type tries: int 19 | :param delay: initial delay between retries in seconds 20 | :type delay: int 21 | :param backoff: backoff multiplier e.g. value of 2 will double the delay 22 | each retry 23 | :type backoff: int 24 | :param ExceptionToRaise: exceptions that should be raised instead of retried. 25 | 26 | """ 27 | def deco_retry(f): 28 | 29 | @wraps(f) 30 | def f_retry(*args, **kwargs): 31 | mtries, mdelay = tries, delay 32 | while mtries > 1: 33 | try: 34 | return f(*args, **kwargs) 35 | except ExceptionToRaise as e: 36 | raise e 37 | except ExceptionToCheck as e: 38 | if mtries == 1: # only show full stack trace on last try 39 | logger.exception(f"Exception: {e}") 40 | logger.warning(f"Exception: {e}") 41 | logger.info(f"retrying in {mdelay} seconds") 42 | sleep(mdelay) 43 | mtries -= 1 44 | mdelay *= backoff 45 | return f(*args, **kwargs) 46 | 47 | return f_retry # true decorator 48 | 49 | return deco_retry -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Chatstack 2 | 3 | ## Minimalist Context Management for message-based GPTs 4 | 5 | This Python code provides a chatbot implementation with context management using OpenAI's GPT-3.5-turbo or GPT-4 chat models. The chatbot maintains a conversation history and help manages the context state and size in tokens. 6 | 7 | ### Dependencies 8 | 9 | - loguru 10 | - pydantic 11 | - openai 12 | - tiktoken 13 | 14 | ### OPEN_API_KEY 15 | 16 | Chatstack finds your OpenAI API key via the OPENAI_API_KEY environment variable. 17 | 18 | ### Classes 19 | 20 | - `ChatRoleMessage`: A base data class for messages with role, text, and tokens. 21 | - `SystemMessage`: A data class for representing a message with the 'system' role. 22 | - `ContextMessage`: A data class representing additional information context for the model. 23 | - `AssistantMessage`: A data class for representing a message with the 'assistant' role . 24 | - `UserMessage`: A data class for representing a message with the 'user' role. 25 | - `ChatContext`: A class that manages the conversation context and generates responses using OpenAI message interface models. 26 | - `ChatReponse`: A data class that contains the model response to a user message along with a record of the input context sent to the model, and other significant details such as the model used, the number of tokens used, and the estimated cost of the request. 27 | 28 | ### Usage 29 | 30 | 1. Import the `ChatContext` class. 31 | 2. Create an instance of the `ChatContext` class with the desired configuration. 32 | 3. Call the `user_message` or `user_message_stream` methods with the user's message text to get a response from the chatbot. 33 | 34 | Example: 35 | 36 | ```python 37 | from chatstack import ChatContext 38 | 39 | BASE_SYSTEM_PROMPT = "You are a clever bot. Do not apologize, or make excuses. " 40 | BASE_SYSTEM_PROMPT += "Do not mention that you are an AI language model since that is annoying to users." 41 | 42 | def main(): 43 | chat_context = ChatContext(base_system_msg_text=BASE_SYSTEM_PROMPT) 44 | 45 | print("Welcome to the Chatbot!") 46 | 47 | while True: 48 | user_input = input("You: ") 49 | print("Chatbot:") 50 | response = chat_context.user_message(user_input, stream=True) 51 | print(response.text) 52 | 53 | 54 | if __name__ == "__main__": 55 | main() 56 | ``` 57 | 58 | 59 | ### Configuration 60 | 61 | The `ChatContext` class accepts the following parameters: 62 | 63 | - `min_response_tokens`: Minimum number of tokens to reserve for model completion response. 64 | - `max_response_tokens`: Maximum number of tokens to allow for model completion response. 65 | - `chat_context_messages`: Number of recent assistant and user messages to keep in context. 66 | - `model`: The name of the GPT model to use (default: "gpt-3.5-turbo"). 67 | - `temperature`: The temperature for the model's response generation. 68 | - `base_system_msg_text`: The base system message text to provide context for the model. 69 | 70 | The primary method of the ChatContext is the user_message() which is used to assemble the input context to the model and generate a completion. 71 | 72 | 73 | ### `user_message(msg_text: str) -> ChatResponse` 74 | 75 | This method takes a user's message text as input and generates a response from the chatbot using the conversation context. 76 | 77 | ### `user_message_stream(msg_text: str) -> ChatResponse` 78 | 79 | This method is a generator that takes a user's message text as input and yields `ChatResponse` objects containing the incremental and cumulative response text from the chatbot using the conversation context. 80 | 81 | 82 | ### `add_message(msg : ChatRoleMessage)` 83 | 84 | Add a message to the context for presentation to the model in subsequent completion requests. 85 | 86 | #### Parameters: 87 | 88 | - `msg_text` (str): The text of the user's message. 89 | 90 | #### Returns: 91 | 92 | - `ChatResponse`: An instance of the `ChatResponse` data class that includes the model response text, the actual input messages sent to the model, and other relevant details such as the token counts and estimated price of the completion. 93 | 94 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | Apache License 2 | Version 2.0, January 2004 3 | http://www.apache.org/licenses/ 4 | 5 | TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION 6 | 7 | 1. Definitions. 8 | 9 | "License" shall mean the terms and conditions for use, reproduction, 10 | and distribution as defined by Sections 1 through 9 of this document. 11 | 12 | "Licensor" shall mean the copyright owner or entity authorized by 13 | the copyright owner that is granting the License. 14 | 15 | "Legal Entity" shall mean the union of the acting entity and all 16 | other entities that control, are controlled by, or are under common 17 | control with that entity. For the purposes of this definition, 18 | "control" means (i) the power, direct or indirect, to cause the 19 | direction or management of such entity, whether by contract or 20 | otherwise, or (ii) ownership of fifty percent (50%) or more of the 21 | outstanding shares, or (iii) beneficial ownership of such entity. 22 | 23 | "You" (or "Your") shall mean an individual or Legal Entity 24 | exercising permissions granted by this License. 25 | 26 | "Source" form shall mean the preferred form for making modifications, 27 | including but not limited to software source code, documentation 28 | source, and configuration files. 29 | 30 | "Object" form shall mean any form resulting from mechanical 31 | transformation or translation of a Source form, including but 32 | not limited to compiled object code, generated documentation, 33 | and conversions to other media types. 34 | 35 | "Work" shall mean the work of authorship, whether in Source or 36 | Object form, made available under the License, as indicated by a 37 | copyright notice that is included in or attached to the work 38 | (an example is provided in the Appendix below). 39 | 40 | "Derivative Works" shall mean any work, whether in Source or Object 41 | form, that is based on (or derived from) the Work and for which the 42 | editorial revisions, annotations, elaborations, or other modifications 43 | represent, as a whole, an original work of authorship. For the purposes 44 | of this License, Derivative Works shall not include works that remain 45 | separable from, or merely link (or bind by name) to the interfaces of, 46 | the Work and Derivative Works thereof. 47 | 48 | "Contribution" shall mean any work of authorship, including 49 | the original version of the Work and any modifications or additions 50 | to that Work or Derivative Works thereof, that is intentionally 51 | submitted to Licensor for inclusion in the Work by the copyright owner 52 | or by an individual or Legal Entity authorized to submit on behalf of 53 | the copyright owner. For the purposes of this definition, "submitted" 54 | means any form of electronic, verbal, or written communication sent 55 | to the Licensor or its representatives, including but not limited to 56 | communication on electronic mailing lists, source code control systems, 57 | and issue tracking systems that are managed by, or on behalf of, the 58 | Licensor for the purpose of discussing and improving the Work, but 59 | excluding communication that is conspicuously marked or otherwise 60 | designated in writing by the copyright owner as "Not a Contribution." 61 | 62 | "Contributor" shall mean Licensor and any individual or Legal Entity 63 | on behalf of whom a Contribution has been received by Licensor and 64 | subsequently incorporated within the Work. 65 | 66 | 2. Grant of Copyright License. Subject to the terms and conditions of 67 | this License, each Contributor hereby grants to You a perpetual, 68 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 69 | copyright license to reproduce, prepare Derivative Works of, 70 | publicly display, publicly perform, sublicense, and distribute the 71 | Work and such Derivative Works in Source or Object form. 72 | 73 | 3. Grant of Patent License. Subject to the terms and conditions of 74 | this License, each Contributor hereby grants to You a perpetual, 75 | worldwide, non-exclusive, no-charge, royalty-free, irrevocable 76 | (except as stated in this section) patent license to make, have made, 77 | use, offer to sell, sell, import, and otherwise transfer the Work, 78 | where such license applies only to those patent claims licensable 79 | by such Contributor that are necessarily infringed by their 80 | Contribution(s) alone or by combination of their Contribution(s) 81 | with the Work to which such Contribution(s) was submitted. If You 82 | institute patent litigation against any entity (including a 83 | cross-claim or counterclaim in a lawsuit) alleging that the Work 84 | or a Contribution incorporated within the Work constitutes direct 85 | or contributory patent infringement, then any patent licenses 86 | granted to You under this License for that Work shall terminate 87 | as of the date such litigation is filed. 88 | 89 | 4. Redistribution. You may reproduce and distribute copies of the 90 | Work or Derivative Works thereof in any medium, with or without 91 | modifications, and in Source or Object form, provided that You 92 | meet the following conditions: 93 | 94 | (a) You must give any other recipients of the Work or 95 | Derivative Works a copy of this License; and 96 | 97 | (b) You must cause any modified files to carry prominent notices 98 | stating that You changed the files; and 99 | 100 | (c) You must retain, in the Source form of any Derivative Works 101 | that You distribute, all copyright, patent, trademark, and 102 | attribution notices from the Source form of the Work, 103 | excluding those notices that do not pertain to any part of 104 | the Derivative Works; and 105 | 106 | (d) If the Work includes a "NOTICE" text file as part of its 107 | distribution, then any Derivative Works that You distribute must 108 | include a readable copy of the attribution notices contained 109 | within such NOTICE file, excluding those notices that do not 110 | pertain to any part of the Derivative Works, in at least one 111 | of the following places: within a NOTICE text file distributed 112 | as part of the Derivative Works; within the Source form or 113 | documentation, if provided along with the Derivative Works; or, 114 | within a display generated by the Derivative Works, if and 115 | wherever such third-party notices normally appear. The contents 116 | of the NOTICE file are for informational purposes only and 117 | do not modify the License. You may add Your own attribution 118 | notices within Derivative Works that You distribute, alongside 119 | or as an addendum to the NOTICE text from the Work, provided 120 | that such additional attribution notices cannot be construed 121 | as modifying the License. 122 | 123 | You may add Your own copyright statement to Your modifications and 124 | may provide additional or different license terms and conditions 125 | for use, reproduction, or distribution of Your modifications, or 126 | for any such Derivative Works as a whole, provided Your use, 127 | reproduction, and distribution of the Work otherwise complies with 128 | the conditions stated in this License. 129 | 130 | 5. Submission of Contributions. Unless You explicitly state otherwise, 131 | any Contribution intentionally submitted for inclusion in the Work 132 | by You to the Licensor shall be under the terms and conditions of 133 | this License, without any additional terms or conditions. 134 | Notwithstanding the above, nothing herein shall supersede or modify 135 | the terms of any separate license agreement you may have executed 136 | with Licensor regarding such Contributions. 137 | 138 | 6. Trademarks. This License does not grant permission to use the trade 139 | names, trademarks, service marks, or product names of the Licensor, 140 | except as required for reasonable and customary use in describing the 141 | origin of the Work and reproducing the content of the NOTICE file. 142 | 143 | 7. Disclaimer of Warranty. Unless required by applicable law or 144 | agreed to in writing, Licensor provides the Work (and each 145 | Contributor provides its Contributions) on an "AS IS" BASIS, 146 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or 147 | implied, including, without limitation, any warranties or conditions 148 | of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A 149 | PARTICULAR PURPOSE. You are solely responsible for determining the 150 | appropriateness of using or redistributing the Work and assume any 151 | risks associated with Your exercise of permissions under this License. 152 | 153 | 8. Limitation of Liability. In no event and under no legal theory, 154 | whether in tort (including negligence), contract, or otherwise, 155 | unless required by applicable law (such as deliberate and grossly 156 | negligent acts) or agreed to in writing, shall any Contributor be 157 | liable to You for damages, including any direct, indirect, special, 158 | incidental, or consequential damages of any character arising as a 159 | result of this License or out of the use or inability to use the 160 | Work (including but not limited to damages for loss of goodwill, 161 | work stoppage, computer failure or malfunction, or any and all 162 | other commercial damages or losses), even if such Contributor 163 | has been advised of the possibility of such damages. 164 | 165 | 9. Accepting Warranty or Additional Liability. While redistributing 166 | the Work or Derivative Works thereof, You may choose to offer, 167 | and charge a fee for, acceptance of support, warranty, indemnity, 168 | or other liability obligations and/or rights consistent with this 169 | License. However, in accepting such obligations, You may act only 170 | on Your own behalf and on Your sole responsibility, not on behalf 171 | of any other Contributor, and only if You agree to indemnify, 172 | defend, and hold each Contributor harmless for any liability 173 | incurred by, or claims asserted against, such Contributor by reason 174 | of your accepting any such warranty or additional liability. 175 | 176 | END OF TERMS AND CONDITIONS 177 | 178 | APPENDIX: How to apply the Apache License to your work. 179 | 180 | To apply the Apache License to your work, attach the following 181 | boilerplate notice, with the fields enclosed by brackets "[]" 182 | replaced with your own identifying information. (Don't include 183 | the brackets!) The text should be enclosed in the appropriate 184 | comment syntax for the file format. We also recommend that a 185 | file or class name and description of purpose be included on the 186 | same "printed page" as the copyright notice for easier 187 | identification within third-party archives. 188 | 189 | Copyright 2019 Cogniac Corporation 190 | 191 | Licensed under the Apache License, Version 2.0 (the "License"); 192 | you may not use this file except in compliance with the License. 193 | You may obtain a copy of the License at 194 | 195 | http://www.apache.org/licenses/LICENSE-2.0 196 | 197 | Unless required by applicable law or agreed to in writing, software 198 | distributed under the License is distributed on an "AS IS" BASIS, 199 | WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 200 | See the License for the specific language governing permissions and 201 | limitations under the License. 202 | -------------------------------------------------------------------------------- /chatstack/chatstack.py: -------------------------------------------------------------------------------- 1 | from loguru import logger 2 | from pydantic import BaseModel, root_validator 3 | from typing import Optional, List 4 | from .retry import retry 5 | import openai 6 | import tiktoken 7 | from time import time 8 | import sys 9 | from .pricing import price 10 | from typing import List, Optional, Tuple 11 | 12 | encoder = tiktoken.get_encoding('cl100k_base') 13 | 14 | class ChatRoleMessage(BaseModel): 15 | role: str 16 | text: str 17 | tokens: Optional[int] 18 | 19 | def content(self) -> str: 20 | return self.text 21 | 22 | @root_validator 23 | def compute_tokens(cls, values) -> int: 24 | _text = f'{values["role"]}\n{values["text"]}' 25 | values["tokens"] = len(encoder.encode(_text)) 26 | values["tokens"] += 4 # per https://platform.openai.com/docs/guides/chat/managing-tokens 27 | return values 28 | 29 | 30 | class SystemMessage(ChatRoleMessage): 31 | role = 'system' 32 | text: str 33 | 34 | class ContextMessage(ChatRoleMessage): 35 | """ 36 | A message added to the model input context to provide context for the model. 37 | Generally contains source material from a search function 38 | Includes a prefix header to provide additional context to the model as to the nature of the content 39 | """ 40 | role = 'system' 41 | prefix: str 42 | text: str 43 | 44 | def content(self) -> str: 45 | return f'{self.prefix}: {self.text}' 46 | 47 | @root_validator 48 | def compute_tokens(cls, values) -> int: 49 | _text = f'{values["role"]}\n{values["prefix"]}: {values["text"]}' 50 | values["tokens"] = len(encoder.encode(_text)) 51 | values["tokens"] += 4 # per https://platform.openai.com/docs/guides/chat/managing-tokens 52 | return values 53 | 54 | 55 | class AssistantMessage(ChatRoleMessage): 56 | role = 'assistant' 57 | text: str 58 | 59 | class UserMessage(ChatRoleMessage): 60 | role = 'user' 61 | text: str 62 | 63 | 64 | class ChatResponse(BaseModel): 65 | """ 66 | returned in response to a User Message 67 | contains the complete state of the input context as sent to the model as well as the response from the model 68 | and other details such as the model used, the number of tokens used, and the estimated cost of the request 69 | """ 70 | text: str # the completion response from the model 71 | delta: Optional[str] # the response text delta for streaming case 72 | model: str # the model used to generate the response 73 | temperature: float # the temperature used to generate the response 74 | inputs: List[ChatRoleMessage] # the input context as sent to the model 75 | input_tokens: int # the number of tokens used in the input context 76 | response_tokens: int # the number of tokens in the response text. only valid on last output for streaming 77 | price: float # the estimated price of the request in dollars. only valid on last output for streaming 78 | 79 | 80 | GPT3_MODELS = ['gpt-3.5-turbo', 'gpt-3.5-turbo-0301'] 81 | GPT4_MODELS = ['gpt-4', 'gpt-4-0314', 'gpt-4-1106-preview'] 82 | 83 | class ChatContext: 84 | 85 | def __init__(self, 86 | base_system_msg_text : str = "Please respond to the user request.", # base system message to use for context 87 | min_response_tokens : int = 200, # minimum number of tokens to reserve for model completion response; 88 | max_response_tokens : int = 400, # maximum number of tokens to allow for model completion response; set to None to allow unlimited use of the model context 89 | chat_context_messages : int = 50, # number of recent user/assistant messages to keep in context 90 | model : str = "gpt-3.5-turbo", # model to use for completion 91 | temperature : float = 0.5): # temperature to use for model completion 92 | 93 | self.model = model 94 | self.temperature = temperature 95 | self.base_system_msg = SystemMessage(text=base_system_msg_text) 96 | if model in GPT3_MODELS : 97 | self.max_model_context = 4096 98 | elif model in GPT4_MODELS: 99 | self.max_model_context = 8192 100 | else: 101 | raise ValueError(f"Model {model} not supported. Supported models are {GPT3_MODELS} and {GPT4_MODELS}") 102 | self.min_response_tokens = min_response_tokens 103 | self.max_response_tokens = max_response_tokens 104 | self.chat_context_messages = chat_context_messages 105 | self.messages = [] # reverse chronological order, newest messages first 106 | 107 | 108 | def _assemble_completion_msgs(self, dynamic_context : list[ContextMessage]) -> List[ChatRoleMessage]: 109 | """ 110 | assemble the input messages subject to the following constraints: 111 | must leave room for min_response_tokens in the context 112 | maximum of chat_context_messages user/assistant messages 113 | dynamic_context fills the remaining space 114 | returns list of finalized ChatRoleMessage to feed to model as well as the raw dynamic completion text for future matching purposes 115 | """ 116 | max_input_context = self.max_model_context - self.min_response_tokens 117 | #logger.info(f'maximum input context: {max_input_context} tokens') 118 | chat_messages = [] 119 | chat_tokens = 0 120 | for msg in self.messages[:self.chat_context_messages]: 121 | chat_messages.append(msg) 122 | chat_tokens += msg.tokens 123 | chat_messages.reverse() # put chat messages back in chronological order 124 | #logger.info(f'chat messages: {chat_tokens} tokens') 125 | 126 | # compute the maximum number of tokens to use for dynamic context 127 | max_dynamic_context = max_input_context - chat_tokens - self.base_system_msg.tokens 128 | #logger.info(f'maximum dynamic context: {max_dynamic_context} tokens') 129 | 130 | # assemble dynamic context up to the token limit 131 | dynamic_context_messages = [] 132 | dynamic_context = dynamic_context if dynamic_context else [] 133 | for msg in dynamic_context: 134 | if msg.tokens > max_dynamic_context: 135 | break 136 | dynamic_context_messages.append(msg) 137 | max_dynamic_context -= msg.tokens 138 | 139 | # compose final list of messages 140 | messages = [self.base_system_msg] 141 | messages.extend(dynamic_context_messages) 142 | messages.extend(chat_messages) 143 | # log estimates messages tokens 144 | #logger.info(f'estimated messages tokens: {sum([msg.tokens for msg in messages])}') 145 | return messages 146 | 147 | 148 | @retry(tries=10, delay=.05, ExceptionToRaise=openai.BadRequestError) 149 | def _completion(self, msgs :ChatRoleMessage) -> str: 150 | 151 | messages = [{"role": msg.role, "content": msg.content()} for msg in msgs] 152 | 153 | try: 154 | t0 = time() 155 | response = openai.ChatCompletion.create(model = self.model, 156 | messages = messages, 157 | max_tokens = self.max_response_tokens, 158 | temperature = self.temperature) 159 | except openai.error.RateLimitError as e: 160 | logger.info(f'OpenAI RateLimitError, retrying...') 161 | raise 162 | except Exception as e: 163 | logger.warning(f'Exception during openai.ChatCompletion.create: {e}, retrying...') 164 | raise 165 | response_text = response['choices'][0]['message']['content'] 166 | dt = time() - t0 167 | #logger.info(f'completion time: {dt:.3f} s') 168 | return response_text 169 | 170 | def add_message(self, msg : ChatRoleMessage): 171 | """ 172 | Add a message to the context for presentation to the model in subsequent completion requests. 173 | Does not result in a model completion. 174 | """ 175 | self.messages.insert(0, msg) 176 | 177 | def user_message(self, msg_text : str, dynamic_context : Optional[list[ContextMessage]] = None) -> ChatResponse: 178 | msg = UserMessage(text=msg_text) 179 | # put message at beginning of list 180 | self.messages.insert(0, msg) 181 | completion_msgs = self._assemble_completion_msgs(dynamic_context) 182 | response_text = self._completion(completion_msgs) 183 | response_msg = AssistantMessage(text=response_text) 184 | self.messages.insert(0, response_msg) 185 | 186 | input_tokens = sum([msg.tokens for msg in completion_msgs]) + 2 187 | cr = ChatResponse(text = response_text, 188 | model = self.model, 189 | temperature=self.temperature, 190 | inputs=completion_msgs, 191 | input_tokens=input_tokens, 192 | response_tokens=response_msg.tokens, 193 | price=price(self.model, input_tokens, response_msg.tokens)) 194 | 195 | return cr 196 | 197 | @retry(tries=10, delay=.05, ExceptionToRaise=openai.BadRequestError) 198 | def _completion_stream(self, msgs :ChatRoleMessage) -> ChatResponse: 199 | """ 200 | return tuple of (delta, response, done): 201 | where delta is the incremental response text, 202 | response is the cumulative response text, 203 | and done is True if the completion is complete 204 | """ 205 | cr = ChatResponse(text = "", 206 | delta = "", 207 | model = self.model, 208 | temperature=self.temperature, 209 | inputs=msgs, 210 | input_tokens=sum([msg.tokens for msg in msgs]) + 2 , 211 | response_tokens=0, 212 | price=0) 213 | 214 | oai_messages = [{"role": msg.role, "content": msg.content()} for msg in msgs] 215 | try: 216 | response = openai.chat.completions.create(model=self.model, 217 | messages=oai_messages, 218 | stream=True, 219 | max_tokens = self.max_response_tokens) 220 | for chunk in response: 221 | output = chunk.choices[0].delta.content or '' 222 | if output: 223 | cr.delta = output 224 | cr.text += output 225 | yield cr 226 | 227 | except openai.RateLimitError as e: 228 | logger.warning(f"OpenAI RateLimitError: {e}") 229 | raise 230 | except openai.BadRequestError as e: # too many token 231 | logger.error(f"OpenAI BadRequestError: {e}") 232 | raise 233 | except Exception as e: 234 | logger.exception(e) 235 | raise 236 | resp_msg = AssistantMessage(text=cr.text) 237 | self.messages.insert(0, resp_msg) # add response to context 238 | cr.response_tokens=resp_msg.tokens 239 | cr.price=price(self.model, cr.input_tokens, resp_msg.tokens) 240 | yield cr 241 | 242 | def user_message_stream(self, msg_text, dynamic_context : Optional[list[ContextMessage]] = None) -> ChatResponse: 243 | msg = UserMessage(text=msg_text) 244 | # put message at beginning of list 245 | self.messages.insert(0, msg) 246 | completion_msgs = self._assemble_completion_msgs(dynamic_context) 247 | for cr in self._completion_stream(completion_msgs): 248 | yield cr 249 | 250 | 251 | 252 | --------------------------------------------------------------------------------