O pacote ChatGPT Long Term Memory é uma ferramenta poderosa projetada para capacitar seus projetos com a capacidade de lidar com um grande número de usuários simultâneos. Ele consegue isso integrando perfeitamente uma extensa base de conhecimento e memória adaptativa por meio de tecnologias de ponta, como GPT da OpenAI, índice vetorial de lhama e armazenamento de dados Redis. Com esse conjunto abrangente de recursos, você pode criar aplicativos altamente escaláveis que fornecem conversas contextualmente relevantes e envolventes, melhorando a experiência e a interação geral do usuário.
Escalabilidade : O pacote ChatGPT Long Term Memory foi projetado para lidar com vários usuários simultâneos de forma eficiente, tornando-o adequado para aplicações com alta demanda de usuários.
Ampla base de conhecimento : Beneficie-se da integração de uma base de conhecimento que permite incorporar dados personalizados na forma de arquivos TXT. Esse recurso permite que o sistema forneça respostas contextualmente relevantes e participe de conversas significativas.
Memória adaptativa : o pacote utiliza tecnologias de ponta como GPT, índice vetorial de lhama e armazenamento de dados Redis para garantir um sistema de memória adaptativa. Esse recurso permite melhor desempenho e interações coerentes, tornando as conversas mais naturais e envolventes.
Integração flexível com modelos GPT : O pacote permite interação perfeita com modelos GPT, oferecendo a opção de conversar com modelos GPT usando memória de contexto. Isso permite que você se envolva com modelos de linguagem de última geração para tarefas de processamento de linguagem mais avançadas.
Fácil instalação e configuração : o pacote fornece etapas simples de instalação usando pip
e você pode configurar rapidamente seu ambiente com sua chave API do OpenAI. As opções de configuração são personalizáveis, permitindo adaptar o pacote para atender aos requisitos específicos do seu projeto.
Utilização do Redis Datastore : A integração com o Redis Datastore garante armazenamento e recuperação eficiente de dados, contribuindo para a escalabilidade geral e capacidade de resposta do sistema.
Integração de API com OpenAI : O pacote aproveita a API do OpenAI para potencializar suas funcionalidades baseadas em GPT. Isso garante acesso aos mais recentes avanços em processamento de linguagem e recursos de modelos GPT.
Aprendizado e melhoria contínua : Como um sistema baseado em GPT, o pacote ChatGPT Long Term Memory se beneficia de aprendizado e melhoria contínua, mantendo-se atualizado com os mais recentes desenvolvimentos em compreensão e geração de linguagem.
Fluxo de conversa personalizável : o pacote oferece fluxos de conversa personalizáveis com a capacidade de incluir o histórico de bate-papo do usuário e dados da base de conhecimento. Isto melhora a compreensão contextual e a relevância das respostas.
Interfaces fáceis de usar : Os trechos de código e interfaces fornecidos facilitam aos desenvolvedores a integração do pacote ChatGPT Long Term Memory em seus projetos, minimizando a curva de aprendizado e agilizando o processo de desenvolvimento.
A combinação desses recursos principais torna o pacote ChatGPT Long Term Memory uma adição valiosa aos seus projetos, permitindo criar aplicativos de conversação interativos e dinâmicos com poderosos recursos de processamento de linguagem.
Para utilizar o pacote Chatgpt Long Term Memory em seus projetos, siga as etapas abaixo:
pip install chatgpt_long_term_memory
export OPENAI_API_kEY=sk-******
puxe a imagem do redis docker e execute:
docker pull redis
docker network create --subnet=172.0.0.0/16 mynet123
docker run --name redis-db -d --net mynet123 --ip 172.0.0.22 -p 6379:6379 -p 8001:8001 redis:latest
Você pode aproveitar a memória de índice definindo Knowledge_base=True para incorporar seus dados personalizados na forma de arquivos TXT localizados no diretório: {your_root_path}/resources/data. Garanta o endereçamento adequado do diretório de recursos/dados para acesso contínuo aos dados armazenados.
# example/usage_index_memory.py
from utils import get_project_root
from chatgpt_long_term_memory . conversation import ChatGPTClient
from chatgpt_long_term_memory . llama_index_helpers import ( IndexConfig ,
RetrieversConfig )
from chatgpt_long_term_memory . memory import ChatMemoryConfig
# Get project's root path
root_path = get_project_root ()
"""
First:
Initialize llama indexes config to create a index from knowledge base and user's chat history.
The root_path specifies the directory where the index will be stored.
The knowledge_base flag specifies whether to index the knowledge base.
The model_name specifies the name of the language model to use for indexing.
The temperature parameter controls the randomness of the output.
The context_window parameter specifies the size of the context window to use for indexing.
The num_outputs parameter specifies the number of output tokens to generate for each input token.
The max_chunk_overlap parameter specifies the maximum overlap between chunks.
The chunk_size_limit parameter specifies the maximum size of a chunk.
"""
doc_indexer_config = IndexConfig (
root_path = f" { root_path } /example" ,
knowledge_base = True ,
model_name = "gpt-3.5-turbo" ,
temperature = 0 ,
context_window = 4096 ,
num_outputs = 700 ,
max_chunk_overlap = 0.5 ,
chunk_size_limit = 600
)
"""
Second:
# Initialize retrievers config to configure the retrievers class.
# The `top_k` parameter specifies the number of top-k documents to retrieve for each query.
# The `max_tokens` parameter specifies the maximum number of tokens to return for each document.
"""
retrievers_config = RetrieversConfig (
top_k = 7 ,
max_tokens = 1000
)
"""
Then:
Initialize chat memory config to configure the chat memory class.
The `redis_host` parameter specifies the hostname of the Redis server.
The `redis_port` parameter specifies the port of the Redis server.
"""
chat_memory_config = ChatMemoryConfig (
redis_host = "172.0.0.22" ,
redis_port = 6379
)
"""
Create a `ChatGPTClient` object to start the conversation.
The `doc_indexer_config` parameter specifies the configuration for the document indexer.
The `retrievers_config` parameter specifies the configuration for the retrievers.
The `chat_memory_config` parameter specifies the configuration for the chat memory.
"""
chatgpt_client = ChatGPTClient (
doc_indexer_config = doc_indexer_config ,
retrievers_config = retrievers_config ,
chat_memory_config = chat_memory_config
)
# Start a conversation with the user.
user_id = 1
while True :
# Get the user's input.
user_input = input ( "User Input:" )
# If the user enters "q", break out of the loop.
if user_input == "q" :
break
# Get the response from the chatbot.
index , response = chatgpt_client . converse ( user_input , user_id = user_id )
# Print the response to the user.
print ( response )
Nesse cenário, você não pode usar seu próprio banco de dados, mas pode interagir com os modelos GPT e usar memória de contexto.
# example/usage_context_memory.py
from utils import get_project_root
from chatgpt_long_term_memory . conversation import ChatbotClient
from chatgpt_long_term_memory . llama_index_helpers import ( IndexConfig ,
RetrieversConfig )
from chatgpt_long_term_memory . memory import ChatMemoryConfig
from chatgpt_long_term_memory . openai_engine import OpenAIChatConfig
# Get project's root path
root_path = get_project_root ()
"""
First:
Initialize llama indexes config to create a index from knowledge base and user's chat history.
The root_path specifies the directory where the index will be stored.
The knowledge_base flag specifies whether to index the knowledge base.
The model_name specifies the name of the language model to use for indexing.
The temperature parameter controls the randomness of the output.
The context_window parameter specifies the size of the context window to use for indexing.
The num_outputs parameter specifies the number of output tokens to generate for each input token.
The max_chunk_overlap parameter specifies the maximum overlap between chunks.
The chunk_size_limit parameter specifies the maximum size of a chunk.
"""
doc_indexer_config = IndexConfig (
root_path = f" { root_path } /example" ,
knowledge_base = True ,
model_name = "gpt-3.5-turbo" ,
temperature = 0 ,
context_window = 4096 ,
num_outputs = 700 ,
max_chunk_overlap = 0.5 ,
chunk_size_limit = 600
)
"""
Second:
# Initialize retrievers config to configure the retrievers class.
# The `top_k` parameter specifies the number of top-k documents to retrieve for each query.
# The `max_tokens` parameter specifies the maximum number of tokens to return for each document.
"""
retrievers_config = RetrieversConfig (
top_k = 7 ,
max_tokens = 1000
)
"""
Then:
Initialize chat memory config to configure the chat memory class.
The `redis_host` parameter specifies the hostname of the Redis server.
The `redis_port` parameter specifies the port of the Redis server.
"""
chat_memory_config = ChatMemoryConfig (
redis_host = "172.0.0.22" ,
redis_port = 6379
)
# Method 2: chat with gpt models, use context memory in this scenario you can't use your own db
openai_chatbot_config = OpenAIChatConfig (
model_name = "gpt-4" ,
max_tokens = 1000 ,
temperature = 0 ,
top_p = 1 ,
presence_penalty = 0 ,
frequency_penalty = 0 ,
# keep in mind if you change prompt, consider history and human input
prompt = """Assistant is a large language model trained by OpenAI.
Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-like text based on the input it receives, allowing it to engage in natural-sounding conversations and provide responses that are coherent and relevant to the topic at hand.
Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based on the input it receives, allowing it to engage in discussions and provide explanations and descriptions on a wide range of topics.
Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.
History: {}
Human: {}
Assistant:"""
)
# Initialize the chatbot client.
chat_app = ChatbotClient (
doc_indexer_config = doc_indexer_config ,
retrievers_config = retrievers_config ,
chat_memory_config = chat_memory_config ,
openai_chatbot_config = openai_chatbot_config
)
# Start a conversation with the user.
user_id = 2
while True :
# Get the user's input.
user_input = input ( "User Input:" )
# If the user enters "q", break out of the loop.
if user_input == "q" :
break
# Get the response from the chatbot.
index , response = chat_app . converse ( user_input , user_id = user_id )
# Print the response to the user.
print ( response )