Spaces:
No application file
No application file
| """ | |
| Data Scientist.: Dr.Eddy Giusepe Chirinos Isidro 🤗 | |
| Começamos executando os scripts da seguinte maneira: | |
| * python main.py | |
| * streamlit run main_st.py | |
| * python main_gr.py | |
| * python main_gr_chat.py | |
| """ | |
| import sys | |
| import tiktoken | |
| import openai | |
| import os | |
| from dotenv import load_dotenv, find_dotenv | |
| _ = load_dotenv(find_dotenv()) # read local .env file | |
| openai.api_key = os.environ['OPENAI_API_KEY'] | |
| # Definimos a função para contar tokens: | |
| def count_tokens(text): | |
| encoding = tiktoken.encoding_for_model("gpt-3.5-turbo") | |
| return len(encoding.encode(text)) | |
| # Defina o limite máximo de tokens: | |
| MAX_MEMORY_TOKENS = 50 # Sempre certifique-se de que ainda está dentro do limite de contexto --> ~8000 | |
| # Inicialize a lista 'conversation_history': | |
| conversation_history = [ | |
| {"role": "system", "content": "Você é um assistente prestativo."} | |
| ] | |
| # O loop principal do chatbot: | |
| while True: | |
| # Obtemos o input do usuário: | |
| chat_input = input("Você: ") | |
| # # Check if the user wants to print the entire chat history | |
| # if chat_input.lower() == "print chat history": | |
| # print_chat_history = True | |
| # else: | |
| # print_chat_history = False | |
| # Anexe a entrada do usuário ao histórico de conversas: | |
| conversation_history.append({"role": "user", "content": chat_input}) | |
| # Calculamos o total de TOKENS no histórico de conversas: | |
| total_tokens = sum(count_tokens(message["content"]) for message in conversation_history) | |
| print(f"Total de TOKENS antes da remoção: {total_tokens}") | |
| # Remova a mensagem mais antiga do histórico de conversas se o total de TOKENS exceder o limite máximo: | |
| while total_tokens > MAX_MEMORY_TOKENS: | |
| if len(conversation_history) > 2: | |
| removed_message = conversation_history.pop(1) # Remove e retornar um elemento de uma lista com base em um índice específico. Se for vazio .pop() ele removerá e retornará o último elemento da lista por padrão. | |
| total_tokens -= count_tokens(removed_message["content"]) | |
| # Imprime o total de tokens usados após remover a mensagem mais antiga | |
| else: | |
| break | |
| print(f"Total de TOKENS após remoção: {total_tokens}") | |
| # Faça chamadas de API para OpenAI com o histórico de conversas e use respostas de streaming: | |
| print("Prestes a enviar solicitação") | |
| response = openai.ChatCompletion.create(model="gpt-4", # or gpt-3.5-turbo | |
| messages=conversation_history, | |
| stream=True, | |
| ) | |
| print("Receba a resposta!") | |
| # Processe a resposta da API: | |
| for chunk in response: | |
| if "role" in chunk["choices"][0]["delta"]: | |
| continue | |
| elif "content" in chunk["choices"][0]["delta"]: | |
| r_text = chunk["choices"][0]["delta"]["content"] | |
| conversation_history.append({"role": "assistant", "content": r_text}) | |
| sys.stdout.write(r_text) # Escreverá o conteúdo da variável r_text no console ou em qualquer outro destino associado ao fluxo de saída padrão. | |
| sys.stdout.flush() # é usado para forçar a saída imediata de qualquer texto armazenado no buffer de saída (normalmente associado ao console). | |
| # Nova linha após a resposta do assistente | |
| print() | |