Package: gpt-term
Chat with GPT in TerminalThis project enables chatting with ChatGPT in the terminal.Markdown content in answers is rendered as beautifully formatted rich text.Supports history retrieval with the up arrow key, optional multi-line questions, and tokens counting.Slash (/) commands are available in the chat box to toggle multi-line submit mode, undo the last question and answer, modify the system prompt and more, see the available commands below for details.Supports saving chat messages to a JSON file and loading them from the file.Uses thegpt-3.5-turbomodel, which is the same model used by ChatGPT (Free Edition), as default.Related ProjectsGPTerm implemented in C/C++by @Ace-Radomgpt-term that can call POE APIby @Lemon-2333Changelog2023-11-17Added the feature of setting the default model. Now you can usegpt-term --set-model MODEL_NAMEto set the default model. This setting will be written into the configuration file and will take effect every time it is started.Added new model candidates:gpt-4-1106-preview,gpt-4-vision-preview,gpt-3.5-turbo-1106.2023-06-21Added direct query mode, now you can rungpt-termwith the content of the question as a parameter to conduct a single question and answergpt-term"What's the weather like today?"The answer will be printed directly, or piped into a variablegpt-term"What's the weather like today"|readanswerecho$answerMore Change log2023-05-20Added host configuration support, which is very useful when using self-built API reverse proxy server (#49), you can now usegpt-term --set-host HOSTto configure host, the default ishttps://api.openai.com2023-05-18Added multi-language support: English, Chinese, Japanese, German, follow the system language by default, now you can use/langto switch languages2023-05-11Find the command the user most likely intended to enter when typing an unrecognized command2023-05-05Add/randcommand to set temperature parameterAdd overflow mode switch for/streamcommand, now you can run command/stream visibleto switch to always visible mode. In this mode, the content that exceeds the screen will be scrolled up, and the new content will be output until it is completed2023-04-23Releasedgpt-termonPypi, started version control. No need to clone the project locally anymore, simply use thepipcommand to install gpt-term.2023-04-15Added the ability to create a line break in single-line mode usingEsc+Enter2023-04-13Added the function of generating and setting the terminal title in the background, and now the client will use the summary of the first question content as the terminal title2023-04-09Add filename generate function, client will suggest the summary of the first question as filename when save command executed.2023-04-05Add/deletecommand to delete the first question and answer in this chat to reduce token.2023-04-01Add/copycommand to copy the last reply's content to the clipboardAdd streaming output mode, enabled by default, use/streamto switch2023-03-28Add--modelruntime argument and/modelcommand to choose / change AI models.2023-03-27Added--keyruntime argument to select which API key in the.envfile to use.2023-03-23Added slash (/) command functionalityAdded--loadruntime argument to load previously saved chat historyModified program structure and interaction methods, changing the originalinput()function to theprompt_toolkitlibrary's input interface, supporting multi-line input, command-line completion, and other features.Improved error handling mechanisms, added chat history backup, logging, and other features, enhancing the program's reliability and fault tolerance.Refactored code logic and function structure, improving modularity and readability.PreparationAn OpenAI API key. You need to register an OpenAI account and obtain an API key.OpenAI's API key can be generated on the page opened by clicking "View API keys" in the upper right corner of the homepage, direct link:https://platform.openai.com/account/api-keysPythonversion 3.7 or higher.Attention: Try not to use the Python that comes with the system (including Windows 11 app store version and MacOS pre-installed Python), otherwise the gpt-term command will not be found after installation (#38)InstallationInstallGPT-Termusingpippip3installgpt-termConfigure the API Keygpt-term--set-apikeyYOUR_API_KEYIf you don't configure the API Key now, you can enter it when prompted during runtime.UpdateTo updateGPT-Termto the latest version, run the following command in your terminal:pip3install--upgradegpt-termIf there is a new version,GPT-Termwill prompt the user to update upon exiting.How to UseRun with the following command:gpt-termOr:python3-mgpt_termQuick query:gpt-term"What's the weather like today?"When entering a question in single-line mode, useEsc+Enterto start a new line, and useEnterto submit the question.Here are some common shortcut keys (also shortcut keys for the shell):Ctrl+_:	UndoCtrl+L: Clear screen, equivalent toclearcommand in shellCtrl+C: Stop the current answer or cancel the current inputTab: Autocomplete commands or parametersCtrl+U: Delete all characters to the left of the cursorCtrl+K: Delete all characters to the right of the cursorCtrl+W: Delete the word to the left of the cursorOriginal chat logs will be saved to~/.gpt-term/chat.logAvailable ArgumentsArgumentsDescriptionExamples-h, --helpshow this help message and exitgpt-term --help--load FILELoad chat history from filegpt-term --load chat_history_code_check.json--key API_KEYSelect the API key to use in the config.ini filegpt-term --key OPENAI_API_KEY1--model MODELSelect AI model to usegpt-term --model gpt-3.5-turbo--host HOSTSet the API Host address used in this run (this is usually used to configure proxy)gpt-term --host https://closeai.deno.dev-m, --multiEnable multiline modegpt-term --multi-r, --rawEnable raw modegpt-term --raw-l, --lang LANGSet the current running language: en, zh_CN, jp, degpt-term --lang en--set-model HOSTSet the AI model to usegpt-term --set-model gpt-4-1106-preview--set-host HOSTSet API Host address (this is usually used to configure proxy)gpt-term --set-host https://closeai.deno.dev--set-apikey KEYSet OpenAI API keygpt-term --set-apikey sk-xxx--set-timeout SECSet the maximum wait time for API requestsgpt-term --set-timeout 10--set-gentitle BOOLSet whether to auto-generate title for chatgpt-term --set-gentitle True--set-saveperfix PERFIXSet the save prefix for chat history filesgpt-term --set-saveperfix chat_history_--set-loglevel LEVELSet log level: DEBUG, INFO, WARNING, ERROR, CRITICALgpt-term --set-loglevel DEBUG--set-lang LANGSet language: en, zh_CN, jp, degpt-term --set-lang enMulti-line mode and raw mode can be used simultaneouslyConfiguration FileThe configuration file is located at~/.gpt-term/config.iniand is autogenerated. It can be modified using the program's--setoption or edited manually.The default configuration is as follows:[DEFAULT]# API key for OpenAIOPENAI_API_KEY=# The maximum waiting time for API requests, the default is 30sOPENAI_API_TIMEOUT=30# Whether to automatically generate titles for conversations, enabled by default (generating titles will consume a small amount of tokens)AUTO_GENERATE_TITLE=True# Define the default file prefix when the /save command saves the chat history. The default value is "./chat_history_", which means that the chat history will be saved in the file starting with "chat_history_" in the current directory# At the same time, the prefix can also be specified as a directory + / to allow the program to save the chat history in a folder (note that the corresponding folder needs to be created in advance), for example: CHAT_SAVE_PERFIX=chat_history/CHAT_SAVE_PERFIX=./chat_history_# Log level, default is INFO, available value: DEBUG, INFO, WARNING, ERROR, CRITICALLOG_LEVEL=INFO# Set the language of the program, the default is empty, it will follow the system languageLANGUAGE=# 设置api的host，默认为https://api.openai.comOPENAI_HOST=# 设置使用的模型，默认为gpt-3.5-turbo# 可用模型: https://platform.openai.com/docs/models/gpt-4-and-gpt-4-turbo, https://platform.openai.com/docs/models/gpt-3-5OPENAI_MODEL=Available Commands/raw: Display raw text in replies instead of rendered Markdown formatAfter switching, use the/lastcommand to reprint the last reply/multi: Enable or disable multi-line mode, allowing users to enter multi-line textIn multi-line mode, useEsc+Enterto submit the questionIf pasting multi line text, single-line mode can also paste properly/stream: disable or enable stream modeIn stream mode, the answer will start outputting as soon as the first response arrives, which can reducing waiting time. Stream mode is on by default./stream ellipsis(default)Switch the mode of streaming output to auto omission, when the output content exceeds the screen, three small dots will be displayed at the bottom of the screen and wait until the output is completed/stream visibleToggle the streaming output mode to always visible, in this mode, the content that exceeds the screen will be scrolled up, and the new content will be output until it is completed. Note that in this mode the terminal will not properly clean up off-screen content./tokens: Display the total tokens spent and the tokens for the current conversationGPT-3.5 has a token limit of 4096; use this command to check if you're approaching the limit/usage: Display the API credits summaryThis feature may not be stable. If it fails to operate, you can visit theusage pageto view further information./model: Show or change the Model in usegpt-4,gpt-4-32k,gpt-3.5-turboare supported by default. when using other models you need to change the API endpoint in code./last: Show the last reply/copyor/copy all: Copy the last reply's content to the clipboard/copy code [index]: Copy theindex-th code block from the last reply's content to the clipboardIfindexis not specified, the terminal will print all code blocks and ask for the number of the one to be copied/deleteor/delete first: delete the first question and answer in the current chatWhen the token is about to reach the upper limit, the user will be warned, and when the upper limit has been exceeded, it will be asked whether to delete the first message/delete all: delete all messages/save [filename_or_path]: Save the chat history to the specified JSON fileIf no filename or path is provided, the client will generate one, and if generation fails, the filenamechat_history_YEAR-MONTH-DAY_HOUR,MINUTE,SECOND.jsonis suggested on input./system [new_prompt]: Modify the system prompt/rand [randomness]: Set Model sampling temperature (0~2), higher values like 0.8 will make the output more random, while lower values like 0.2 will make it more focused and deterministic./title [new_title]: Set terminal title for this chatIf new_title is not provided, a new title will be generated based on first question/timeout [new_timeout]: Modify API timeout.The default timeout is 30 seconds, it can also be configured by settingOPENAI_API_TIMEOUT=in the~/.gpt-term/config.inifile./undo: Delete the previous question and answer/version: Display the local and remote versions ofGPT-Term/help: Display available commands/exit: Exit the applicationExit WordsIn the chat, use exit words to end the current session. Exit words include:['再见','bye','goodbye','结束','end','退出','exit','quit']Exit words will be sent as a question to ChatGPT, and the application will exit after GPT replies.You can also useCtrl-Dor/exitto exit immediately.Upon exit, the token count for the chat session will be displayed.Current price: $0.002 / 1K tokens, Free Edition rate limit: 20 requests / min (gpt-3.5-turbo)DependenciesThanks to the following projects for providing strong support for this script:requests: For handling HTTP requestspyperclip: A cross-platform clipboard operation libraryrich: For outputting rich text in the terminalprompt_toolkit: Command-line input processing librarysseclient-py: For implementing streaming output of answerstiktoken: A library for calculating and processing OpenAI API tokensContributingFeel free to dive in!Open an issueor submit PRs.ContributorsThis project exists thanks to all the people who contribute.Project Structure.
├──LICENSE# License├──README.md# Documentation├──chat.py# Script entry point├──gpt_term# Project package folder│├──__init__.py
│├──config.ini# API key storage and other settings│└──main.py# Main program├──requirements.txt# List of dependencies└──setup.pyLicenseThis project is licensed under theMIT License.