Last active
June 13, 2023 02:40
-
-
Save viniciusgonmelo/599e716cf3702125f46922753f78dc63 to your computer and use it in GitHub Desktop.
Interação com o ChatGPT no shell
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env python3 | |
# Script: shell_chatgpt.py | |
# Descrição: Interaja com o ChatGPT da OpenAI no shell | |
# Opções: | |
# -m, --model: Nome do modelo GPT a ser usado (padrão: "gpt-3.5-turbo"). | |
# -t, --temperature: Valor da temperatura para controlar a aleatoriedade das respostas (padrão: 0.5). | |
import sys | |
import openai | |
import getpass | |
import argparse | |
import time | |
import random | |
from os.path import expanduser | |
from prompt_toolkit import PromptSession | |
from prompt_toolkit.history import FileHistory | |
from prompt_toolkit.formatted_text import HTML | |
HISTORY_FILE = expanduser("~/.chatgpt_history") | |
def type_text(text, base_speed=0.01, speed_variation=0.0025, | |
speed_increase=0.003, whole_word_probability=0.1, | |
whole_word_speedup=2.0): | |
"""Saída do texto com efeito de máquina de escrever.""" | |
current_speed = base_speed | |
skip_whole_word = False | |
for j, char in enumerate(text): | |
if j == 0 and char == ' ': | |
continue | |
sys.stdout.write(char) | |
sys.stdout.flush() | |
skip_whole_word = char == ' ' and random.random() < whole_word_probability | |
current_speed = max(base_speed, current_speed + speed_increase) if char == '.' else current_speed | |
if not skip_whole_word: | |
delay = current_speed + random.uniform(-speed_variation, speed_variation) | |
time.sleep(delay) | |
if skip_whole_word and char == ' ': | |
time.sleep(current_speed / whole_word_speedup) | |
def chat_gpt_interactive(model_name, temperature): | |
"""Inicia a conversa com o ChatGPT.""" | |
print("Bem-vindo ao ChatGPT!\n") | |
try: | |
openai.api_key = getpass.getpass("Insira sua chave API da OpenAI: ") | |
except KeyboardInterrupt: | |
print("\n\nObrigado por usar o ChatGPT!") | |
sys.exit(0) | |
messages = [] | |
session = PromptSession(history=FileHistory(HISTORY_FILE)) | |
while True: | |
try: | |
user_input = session.prompt(HTML("<b>~</b> ")) | |
messages.append({"role": "user", "content": user_input}) | |
retry = 0 | |
chat_gpt_response = None | |
time.sleep(0.5) | |
# Tenta obter resposta da API do OpenAI | |
while retry < 5: | |
try: | |
response = openai.ChatCompletion.create( | |
model=model_name, | |
messages=messages, | |
temperature=temperature, | |
) | |
chat_gpt_response = response.choices[0].message["content"].lstrip() | |
break | |
except openai.error.RateLimitError: | |
retry += 1 | |
time.sleep(1.5 ** retry) | |
if chat_gpt_response is None: | |
print("Falha ao obter resposta após 5 tentativas") | |
continue | |
print(f"\033[1mChatGPT ({model_name}):\033[0m ", end='') | |
type_text(chat_gpt_response) | |
print() | |
messages.append({"role": "assistant", "content": chat_gpt_response}) | |
except KeyboardInterrupt: | |
print("\nObrigado por usar o ChatGPT!") | |
break | |
except Exception as e: | |
print(f"Erro: {e}") | |
break | |
def main(): | |
"""Função principal que lida com argumentos da linha de comando e inicia a sessão interativa.""" | |
parser = argparse.ArgumentParser(description="Interaja com o ChatGPT no shell.") | |
parser.add_argument("-m", "--model", default="gpt-3.5-turbo", help="Nome do modelo GPT a ser usado.") | |
parser.add_argument("-t", "--temperature", type=float, default=0.5, help="Valor da temperatura para controlar a aleatoriedade das respostas.") | |
args = parser.parse_args() | |
try: | |
chat_gpt_interactive(args.model, args.temperature) | |
except ValueError as e: | |
print(f"Erro: {e}") | |
if __name__ == "__main__": | |
main() |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
FROM python:3.9-slim-buster | |
LABEL name="my-chatgpt" | |
# Exemplo de Dockerfile para o shell-chatgpt | |
RUN apt-get update && \ | |
apt-get install -y openssh-server && \ | |
useradd -rm -s /bin/bash chatgpt && \ | |
echo 'chatgpt:chatgpt' | chpasswd | |
RUN mkdir -p /run/sshd && \ | |
sed -i 's/#PasswordAuthentication.*/PasswordAuthentication no/' /etc/ssh/sshd_config && \ | |
sed -i 's/#PermitRootLogin.*/PermitRootLogin no/' /etc/ssh/sshd_config | |
RUN pip install --no-cache-dir openai prompt_toolkit | |
COPY chatgpt.py /usr/local/bin/chatgpt | |
RUN chmod +x /usr/local/bin/chatgpt | |
ARG AUTHORIZED_KEYS | |
WORKDIR /home/chatgpt | |
USER chatgpt | |
RUN mkdir .ssh && chmod 700 .ssh && \ | |
touch .ssh/authorized_keys && \ | |
chmod 600 .ssh/authorized_keys && \ | |
echo "$AUTHORIZED_KEYS" > .ssh/authorized_keys | |
USER root | |
EXPOSE 22 | |
CMD ["/usr/sbin/sshd", "-D"] | |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
aiohttp==3.8.4 | |
aiosignal==1.3.1 | |
async-timeout==4.0.2 | |
attrs==23.1.0 | |
certifi==2023.5.7 | |
charset-normalizer==3.1.0 | |
frozenlist==1.3.3 | |
idna==3.4 | |
multidict==6.0.4 | |
openai==0.27.6 | |
prompt-toolkit==3.0.38 | |
requests==2.30.0 | |
tqdm==4.65.0 | |
urllib3==2.0.2 | |
wcwidth==0.2.6 | |
yarl==1.9.2 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment