Aprimorando as conversas de IA com memória LangChain


Think about conversar com um assistente digital que se lembra não apenas da sua última pergunta, mas de todo o fluxo da sua conversa: detalhes pessoais, preferências e até mesmo dúvidas de acompanhamento. Essa memória transforma chatbots de simples máquinas de perguntas e respostas em parceiros de conversação sofisticados, capazes de lidar com tópicos complexos em múltiplas interações. Neste artigo, mergulhamos no fascinante mundo da memória conversacional em Geração Aumentada por Recuperação (RAG), explorando as técnicas que permitem aos chatbots manter o contexto, personalizar respostas e gerenciar consultas em várias etapas de maneira integrada. Você aprenderá sobre diferentes estratégias de memória, suas vantagens e limitações, e até mesmo colocará na prática Pitão e LangChain para ver como esses conceitos funcionam em tempo actual.

Objetivos de aprendizagem

  • Entenda a importância da memória conversacional em sistemas de geração aumentada de recuperação (RAG)⁠.
  • Aprenda sobre diferentes tipos de técnicas de memória de conversação em LangChain, incluindo memória de buffer de conversa⁠, memória de resumo de conversa, memória de janela de buffer de conversa⁠, memória de buffer de resumo de conversa⁠, memória de gráfico de conhecimento de conversa, memória de entidade⁠⁠.
  • Entenda as vantagens e desvantagens de cada técnica de memória⁠⁠.
  • Aprenda como implementar essas técnicas de memória utilizando Python e LangChain⁠.

Este artigo foi publicado como parte do Blogatona de Ciência de Dados.

Importância da memória conversacional em chatbots

A memória conversacional é essential em chatbots e agentes conversacionais porque permite que o sistema mantenha o contexto durante interações prolongadas, tornando as respostas mais relevantes e personalizadas. Em aplicativos baseados em chatbot, especialmente quando a conversa abrange tópicos complexos ou múltiplas consultas, a memória ajuda:

  • Mantendo o Contexto: A memória permite que o modelo se lembre de entradas anteriores, reduzindo questionamentos repetitivos e permitindo respostas suaves e contextualmente conscientes em vários turnos.
  • Melhorando a relevância: Ao lembrar os detalhes específicos de interações passadas, como preferências ou detalhes importantes, o sistema pode recuperar e gerar informações mais relevantes, aumentando a precisão.
  • Aprimorando a personalização: A memória de trocas anteriores permite que os modelos de chatbot adaptem respostas com base em preferências ou escolhas anteriores, melhorando o envolvimento e a satisfação do usuário.
  • Tratamento de consultas em várias etapas: Consultas complexas e de várias etapas que exigem informações de diversas fontes ou documentos se beneficiam da memória, pois permite que o modelo “retenha” respostas provisórias e desenvolva-as de forma lógica.
  • Reduzindo a redundância: A memória reduz a repetição desnecessária, evitando a nova busca ou o reprocessamento de tópicos já discutidos, resultando em uma experiência de usuário mais tranquila.

Memória Conversacional usando Langchain

Existem várias maneiras de incorporar a memória conversacional na geração aumentada de recuperação. No LangChain, todas essas técnicas podem ser executadas através do ConversationChain.

Aprimorando as conversas de IA com memória LangChain

Implementando memória conversacional com Python e LangChain

Iremos nos aprofundar na implementação da memória conversacional usando Python e LangChain, configurando componentes essenciais para permitir que os chatbots se lembrem e consultem trocas anteriores. Abordaremos tudo, desde a criação de tipos de memória até o aprimoramento da relevância das respostas, permitindo que você crie chatbots que lidam com conversas extensas e ricas em contexto sem problemas.

Instalando e importando as bibliotecas necessárias

Para começar, instalaremos e importaremos as bibliotecas necessárias para construir memória conversacional com Python e LangChain. Esta configuração fornecerá as ferramentas necessárias para implementar e testar funções de memória de forma eficaz.

!pip -q set up openai langchain huggingface_hub transformers
!pip set up langchain_community
!pip set up langchain_openai

from langchain_openai import ChatOpenAI
from langchain.chains import ConversationChain
from langchain.reminiscence import ConversationBufferMemory
import os

os.environ('OPENAI_API_KEY') = ''

Memória de buffer de conversa: armazenando histórico completo de interação

Exploraremos como implementar Dialog Buffer Reminiscence, que armazena o histórico completo de interação entre o usuário e o sistema. Este tipo de memória ajuda a reter todas as trocas anteriores, garantindo que o chatbot possa manter o contexto durante toda a conversa, embora possa levar a um maior uso de tokens. Percorreremos o processo de configuração e explicaremos como ele aprimora a capacidade do chatbot de responder com maior relevância.

#Defining the LLM
llm = ChatOpenAI(temperature=0, mannequin="gpt-4o", max_tokens=1000)

dialog = ConversationChain(
    llm=llm,
    verbose=True,
    reminiscence=ConversationBufferMemory()
)
dialog.predict(enter="Hello there! I'm in Miami Right this moment with my fiancee and need to go for procuring.")dialog.predict(enter="How are you in the present day?")
dialog.predict(enter="Are you able to inform me some procuring malls?")
dialog.predict(enter="Are you able to inform me who I'm with in Miami?")#import csv 

Saída:


> Getting into new ConversationChain chain... Immediate after formatting:
The next is a pleasant dialog between a human and an AI. The AI is
talkative and offers a number of particular particulars from its context. If the AI doesn't
know the reply to a query, it in truth says it doesn't know. Present
dialog:

Human: Hello there! I'm in Miami Right this moment with my fiancee and need to go for procuring.
AI: Hiya! That feels like a enjoyable day forward. Miami is a unbelievable place for procuring
with quite a lot of choices to discover. For those who're searching for Luxurious manufacturers and high-
finish style, you may need to take a look at the Bal Harbour Retailers. I For those who're
focused on a extra eclectic combine of retailers, the Miami Design District is a good
alternative. It gives a mix of style, artwork, and design with boutiques like Louis
Vuitton, Dior, and distinctive artwork galleries.

For a extra conventional mall expertise, you may go to the Aventura Mall,
which is without doubt one of the largest malls within the U.S. It has a variety of shops from Zara and H&M
to Nordstrom and Bloomingdale's.
And for those who're searching for one thing extra budget-friendly, the Dolphin Mall is an
outlet mall with quite a lot of shops providing reductions on fashionable manufacturers.
Irrespective of the place you select to go, I am positive you will have a good time procuring in
Miami! Let me know for those who want extra data or have some other questions. Human:
Are you able to inform me some procuring malls?
AI: In fact! Listed below are some fashionable procuring malls in Miami that you just may need to
think about:
1. **Aventura Mall**: As I discussed earlier, this is without doubt one of the largest malls in
the U.S. It options over 300 shops, together with fashionable manufacturers like Apple, Zara, and
Bloomingdale's. It additionally has quite a lot of eating choices and an imp 2. **Dolphin
Mall**: It is a nice choice for outlet procuring, with over 240 shops providing
reductions on manufacturers like Nike, Calvin Klein, and Tommy Hilfiger. It additionally has a
vary of eating and leisure choices, together with a movi 3. **Bal Harbour
Retailers**: Recognized for its luxurious procuring expertise, this open-air mall options
high-end manufacturers like Chanel, Gucci, and Prada. It is set in a wonderful tropical
surroundings, making it a nice place to walk and store 4. **The Retailers at
Merrick Park**: Situated in Coral Gables, this upscale procuring heart gives a mixture
of Luxurious and up to date manufacturers comparable to Neiman Marcus, Nordstrom, and Tiffany &
Co. It additionally has a number of high-quality eating restaur 5. **Brickell Metropolis Centre**:
Located within the coronary heart of Miami's monetary district, this contemporary procuring heart
gives a mixture of high-end and up to date manufacturers, together with Saks Fifth Avenue,
AllSaints, and Sephora. It additionally incorporates a vi 6. **Lincoln Highway Mall**: Whereas not a
conventional mall, this pedestrian road in South Seaside is lined with retailers, cafes,
and eating places. It is an excellent place to benefit from the Miami climate whereas procuring at
shops like H&M, Anthropologie Every of those malls gives a novel procuring
expertise, so it is dependent upon what you are searching for. Get pleasure from your procuring journey
in Miami!
Human: Are you able to inform me who I'm with in Miami?
AI:
> Completed chain.
'You talked about earlier that you're in Miami along with your fiancée. I hope you each have
an exquisite time exploring the town and having fun with your procuring journey! If there's
anything you'd wish to know or some other method I can help you, be happy to
ask.

Vamos verificar o que está armazenado no buffer usando esta função.

print(dialog.reminiscence.buffer)

Saída:

Human: Hello there! I'm in Miami Right this moment with my fiancee and need to go for procuring.
AI: Hiya! That feels like a enjoyable day forward. Miami is a good place for procuring
 with quite a lot of choices to discover. For those who're searching for high-end style and 
luxurious manufacturers, you may need to take a look at Human: Are you able to inform me some procuring
 malls? AI: In fact! Listed below are some fashionable procuring malls in Miami that you just may
 need to go to:
1. **Aventura Mall**: As one of many largest malls in the USA, Aventura 
Mall gives an enormous number of shops, together with each high-end and extra reasonably priced
 manufacturers. You may discover all the pieces from Nords 2. **Dolphin Mall**: It is a great place
 for outlet procuring, with a variety of shops providing reductions on fashionable 
manufacturers. It's kind of extra budget-friendly and consists of shops like Nike, Calvin Klein,
 3. **Brickell Metropolis Centre**: Situated within the coronary heart of Miami's monetary district,
 this contemporary procuring heart options luxurious manufacturers like Saks Fifth Avenue, as effectively
 as quite a lot of eating choices and a ciner 4. **The Falls**: That is an open-air
 procuring heart with a wonderful setting, that includes a waterfall and tropical 
landscaping. It has a mixture of fashionable retailers like Macy's and specialty shops. 5.
 **Dadeland Mall**: Recognized for its giant number of shops, together with
 Macy's, JCPenney, and Nordstrom, Dadeland Mall additionally gives quite a lot of specialty
 retailers and eating choices.
Every of those malls gives a novel procuring expertise, so you may select based mostly on 
your preferences and what you are trying to purchase. Get pleasure from your time in Miami!
Human: Are you able to inform me who I'm with in Miami?
AI: You talked about earlier that you're in Miami along with your fiancée. I hope you each 
have an exquisite time exploring the town and having fun with your procuring journey! If 
there's anything you'd wish to know

As we will see, conversational buffer reminiscence saves each interplay within the chat
 historical past straight. Whereas storing all the pieces provides the LLM the utmost quantity of 
data, extra tokens imply slowing response occasions and better prices.

Memória de resumo de conversa: otimizando o histórico de interação para eficiência

Usando ConversationBufferMemory, usamos muito rapidamente muitos tokens e até excedemos o limite da janela de contexto até mesmo dos LLMs mais avançados disponíveis atualmente. Para evitar o uso excessivo de tokens, podemos usar ConversationSummaryMemory. Como o nome sugere, esta forma de memória resume a história da conversa.

from langchain.chains.dialog.reminiscence import ConversationSummaryMemory
llm = ChatOpenAI(temperature=0, mannequin="gpt-4o", max_tokens=1000)

dialog = ConversationChain(
	llm=llm,
	reminiscence=ConversationSummaryMemory(llm=llm)
)
dialog.predict(enter="Hello there! I'm in Miami Right this moment with my fiancee and need to go for procuring.")
dialog.predict(enter="Are you able to inform me some procuring malls?")
dialog.predict(enter="Are you able to inform me who I'm with in Miami?")

print(dialog.reminiscence.buffer)

Saída:


The human is in Miami with their fiancée and needs to buy groceries. The AI suggests
a number of procuring locations in Miami, together with Bal Harbour Retailers for luxurious
manufacturers, the Miami Design District for a mixture

Passamos o LLM para a função ConversationSummaryMemory, pois o LLM ajuda a resumir os contextos anteriores. Vejamos o immediate que é passado ao LLM para resumir os contextos históricos.

print(dialog.reminiscence.immediate.template)

Saída:


Human: Hello there! I'm in Miami Right this moment with my fiancee and need to go for procuring.
AI: Hiya! That feels like a enjoyable day forward. Miami is a good place for procuring
with quite a lot of choices to discover. For those who're searching for high-end style and
luxurious manufacturers, you may need to take a look at Human: Are you able to inform me some procuring
malls? AI: In fact! Listed below are some fashionable procuring malls in Miami that you just may
need to go to:
1. **Aventura Mall**: As one of many largest malls in the USA, Aventura
Mall gives an enormous number of shops, together with each high-end and extra reasonably priced
manufacturers. You may discover all the pieces from Nords 2. **Dolphin Mall**: It is a great place
for outlet procuring, with a variety of shops providing reductions on fashionable
manufacturers. It's kind of extra budget-friendly and consists of shops like Nike, Calvin Klein,
3. **Brickell Metropolis Centre**: Situated within the coronary heart of Miami's monetary district, this contemporary procuring heart options luxurious manufacturers like Saks Fifth Avenue, as effectively
as quite a lot of eating choices and a ciner 4. **The Falls**: That is an open-air
procuring heart with a wonderful setting, that includes a waterfall and tropical
landscaping. It has a mixture of fashionable retailers like Macy's and specialty shops. 5.
**Dadeland Mall**: Recognized for its giant number of shops, together with
Macy's, JCPenney, and Nordstrom, Dadeland Mall additionally gives quite a lot of specialty
retailers and eating choices.
Every of those malls gives a novel procuring expertise, so you may select based mostly on
your preferences and what you are trying to purchase. Get pleasure from your time in Miami!
Human: Are you able to inform me who I'm with in Miami?
AI: You talked about earlier that you're in Miami along with your fiancée. I hope you each
have an exquisite time exploring the town and having fun with your procuring journey! If
there's anything you'd wish to know

Progressively summarize the traces of dialog offered, including onto the earlier
abstract returning a brand new abstract.
EXAMPLE
Present abstract:
The human asks what the AI thinks of synthetic intelligence. The AI thinks
synthetic intelligence is a pressure for good.
New traces of dialog:
Human: Why do you assume synthetic intelligence is a pressure for good?
AI: As a result of synthetic intelligence will assist people attain their full potential.
New abstract:
The human asks what the AI thinks of synthetic intelligence. The AI thinks
synthetic intelligence is a pressure for good as a result of it would assist people attain their
full potential. END OF EXAMPLE
Present abstract: {abstract}
New traces of dialog:
{new_lines}
New abstract:

Embora a vantagem de usar ConversationSummaryMemory seja que ele reduz o número de tokens para conversas longas, a desvantagem é que toda a memória depende da versão resumida salva da conversa, cuja qualidade varia novamente com a capacidade de resumo do LLM usado.

Memória da janela do buffer de conversa: retendo interações recentes para reconhecimento contextual

A memória da janela do buffer de conversa é semelhante à memória buffer, mas com uma janela predefinida adicionada à memória. Isso significa que apenas pedimos ao modelo para lembrar ‘n’ número de interações anteriores, reduzindo assim o número whole de tokens utilizados em comparação com ConversationBufferMemory.

from langchain.chains.dialog.reminiscence import ConversationBufferWindowMemory
llm = ChatOpenAI(temperature=0, mannequin="gpt-4o", max_tokens=1000)

dialog = ConversationChain(llm=llm,reminiscence=ConversationBufferWindowMemory(okay=3))

dialog.predict(enter="Hello there! I'm in Miami Right this moment with my fiancee and need to go for procuring.")
dialog.predict(enter="Are you able to inform me some procuring malls?")
dialog.predict(enter="Are you able to inform me who I'm with in Miami?")

Saída:


'You talked about earlier that you're in Miami along with your fiancée. I hope you each have
a unbelievable time exploring the town and having fun with all of the procuring and sights
it has to supply! If there's something e lse you'd wish to know or need assistance with,
be happy to ask."

Como podemos ver, com ‘okay’ definido como 3, a modelo consegue lembrar das últimas 3 conversas e portanto consegue lembrar que a pessoa está com sua noiva em Miami.

Se quiser apenas que o nosso chatbot se lembre de uma série de conversas recentes, selecionar este modelo é uma boa escolha. No entanto, esta opção não ajuda o chatbot a lembrar interações muito distantes.

Memória buffer de resumo de conversa: combinando interações recentes com histórico resumido

O ConversationSummaryBufferMemory é uma combinação de ConversationSummaryMemory e ConversationBufferWindowMemory. Este sistema de memória salva as interações recentes em um buffer e combina as mais antigas em um resumo, mantendo ambas armazenadas para uso. Em vez de remover interações mais antigas apenas com base em sua contagem, agora as elimina com base no comprimento whole do token.

from langchain.chains.dialog.reminiscence import ConversationSummaryBufferMemory
llm = ChatOpenAI(temperature=0, mannequin="gpt-4o", max_tokens=1000)

conversation_sum_bufw = ConversationChain(
    llm=llm, reminiscence=ConversationSummaryBufferMemory(
        llm=llm,
        max_token_limit=650
))

conversation_sum_bufw.predict(enter="Hello there! I'm in Miami Right this moment with my fiancee and need to go for procuring.")
conversation_sum_bufw.predict(enter="Are you able to inform me some procuring malls?")
conversation_sum_bufw.predict(enter="Are you able to inform me who I'm with in Miami?")

Saída:


'You might be in Miami along with your fiancée. For those who want any extra data or
suggestions on your journey, be happy to ask!'

Vamos agora verificar como a memória é salva no buffer para esta técnica.

print(conversation_sum_bufw.reminiscence.buffer)

Saída:


System: The human is in Miami with their fiancée and needs to buy groceries. The AI
suggests a number of procuring locations, together with Bal Harbour Retailers, the Miami
Design District, Aventura Mall, and Wynwood. Human: Are you able to inform me who I'm with
in Miami? AI: You might be in Miami along with your fiancée. For those who want any extra data
or suggestions on your journey, be happy to ask!

Como podemos ver na saída acima, a memória buffer possui uma mistura de resumos de conversas distantes anteriores, juntamente com interações reais salvas para as conversas mais recentes.

O ConversationSummaryBufferMemory requer ajustes extras para decidir o que resumir e o que manter no buffer, mas oferece grande flexibilidade na retenção de interações distantes, ao mesmo tempo que mantém as interações recentes em sua forma unique e mais detalhada.

Memória do gráfico de conhecimento de conversação: estruturando informações para contexto aprimorado

Nesta técnica, LangChain constrói um minigráfico de conhecimento de informações conectadas, identificando entidades-chave e seus relacionamentos, ajudando o modelo a compreender e responder melhor a diferentes situações.

from langchain.chains.dialog.reminiscence import ConversationKGMemory
from langchain.prompts.immediate import PromptTemplate

llm = ChatOpenAI(temperature=0, mannequin="gpt-4", max_tokens=1000)
template = """The next is a pleasant dialog between a human and an AI. The AI is talkative and offers a number of particular particulars from its context. 
If the AI doesn't know the reply to a query, it in truth says it doesn't know. The AI ONLY makes use of data contained within the "Related Info" part and doesn't hallucinate.

Related Info:

{historical past}

Dialog:
Human: {enter}
AI:"""
immediate = PromptTemplate(
    input_variables=("historical past", "enter"), template=template
)

conversation_with_kg = ConversationChain(
    llm=llm, 
    verbose=True, 
    immediate=immediate,
    reminiscence=ConversationKGMemory(llm=llm)
)

conversation_with_kg.predict(enter="Hiya, My identify is Myra")
conversation_with_kg.predict(enter="I'm in Miami and want some help in reserving motels.")
conversation_with_kg.predict(enter="I want resort suggestions close to Miami Seashores")

Como visto no código acima, a função ConversationChain é passada com um immediate definido que solicita ao LLM que se concentre apenas nas informações relevantes para uma consulta feita e não tenha alucinações.

import networkx as nx
import matplotlib.pyplot as plt
print(conversation_with_kg.reminiscence.kg.get_triples())

Saída:


(('Myra', 'identify', 'is'), ('Myra', 'Miami', 'is in'), ('Myra', 'reserving motels',
'wants help in'), ('Human', 'resort suggestions close to Miami Seashores',
'want'))

Como pode ser visto na saída acima, na memória, as entidades-chave e seus relacionamentos são salvos. Conseqüentemente, informações estruturadas podem ser facilmente extraídas usando esta técnica.

Memória de entidade: capturando detalhes importantes para respostas personalizadas

A memória de entidade, assim como a memória do Data Graph, extrai detalhes específicos de conversas, como nomes, objetos ou lugares. Este método direcionado ajuda o modelo a responder às perguntas dos usuários com mais precisão.

from langchain.chains.dialog.reminiscence import ConversationEntityMemory
from langchain.chains.dialog.immediate import ENTITY_MEMORY_CONVERSATION_TEMPLATE
## The propmpt
print(ENTITY_MEMORY_CONVERSATION_TEMPLATE.template)

Saída:


'You might be an assistant to a human, powered by a big language mannequin educated by
OpenAI. nnYou are designed to have the ability to help with a variety of duties, from
answering easy inquiries to offering in-d epth explanations and discussions on a
big selection of subjects. As a language mannequin, you'll be able to generate human-like textual content
based mostly on the enter you obtain, permitting you to interact in natural-sounding convers
ations and supply responses which can be coherent and related to the subject at hand.
nnYou are continuously studying and enhancing, and your capabilities are continuously
evolving. You'll be able to course of and un derstand giant quantities of textual content, and might use
this data to supply correct and informative responses to a variety of
questions. You've got entry to some customized data offered by the human
within the Context part under. Moreover, you'll be able to generate your personal textual content
based mostly on the enter you obtain, permitting you to interact in discussions and supply
explanations an

A saída acima mostra o immediate dado ao LLM. Vamos agora ver como ConversationEntityMemory pode ser implementado levando em consideração o modelo de immediate acima.

llm = ChatOpenAI(temperature=0, mannequin="gpt-4o", max_tokens=200)

dialog = ConversationChain(
    llm=llm, 
    verbose=True,
    immediate=ENTITY_MEMORY_CONVERSATION_TEMPLATE,
    reminiscence=ConversationEntityMemory(llm=llm)
)
dialog.predict(enter="Hiya, My identify is Myra")
dialog.predict(enter="I'm in Miami and want some help in reserving motels.")
dialog.predict(enter="I want resort suggestions close to Miami Seashores")

from pprint import pprint
pprint(dialog.reminiscence.entity_store)

Saída:


InMemoryEntityStore (retailer={"Myra': "Myra's identify is Myra.", 'Miami': 'Miami is a
metropolis the place Myra is presently positioned and is in search of help in reserving motels.',
'Miami Seashores': 'Miami Seashores is a popul

Como pode ser visto no resultado acima, todas as entidades relevantes são identificadas mapeadas com os detalhes associados como “’Miami é uma cidade onde Myra está localizada atualmente e está buscando assistência para reservar hotéis.” é mapeado para a entidade “Miami”.

Conclusão

Em sistemas de geração aumentada de recuperação (RAG), a memória conversacional é very important para manter o contexto e melhorar a relevância. Também ajuda a personalizar respostas e lidar com consultas em várias etapas. Ao contrário do RAG ingênuo, que processa cada consulta de forma independente, a memória conversacional constrói uma experiência contínua. Técnicas como Dialog Buffer Reminiscence armazenam históricos completos de interação, mas podem aumentar o uso de tokens. Por outro lado, a memória de resumo de conversas reduz o uso de tokens ao resumir interações anteriores.

A memória da janela do buffer de conversa retém apenas um determinado número de trocas recentes, e a memória do buffer de resumo da conversa combina conversas recentes com resumos das mais antigas, equilibrando contexto e eficiência. Métodos mais avançados, como Dialog Data Graph Reminiscence, estruturam informações como entidades interconectadas, enquanto a Entity Reminiscence captura detalhes específicos, como nomes ou locais, para respostas precisas. Juntas, essas técnicas permitem que os sistemas RAG ofereçam interações contextualmente ricas e adaptáveis, adaptadas às necessidades do usuário.

Principais conclusões

  • A memória conversacional permite que os sistemas RAG mantenham o contexto, melhorando o fluxo e a relevância das interações.
  • Armazenando históricos completos de bate-papo, o Dialog Buffer Reminiscence é útil, mas pode aumentar os custos de token.
  • A memória de resumo de conversas reduz o uso de tokens resumindo efetivamente as interações anteriores.
  • Técnicas híbridas, como Dialog Abstract Buffer Reminiscence, otimizam a memória combinando detalhes recentes e histórico resumido.
  • Técnicas avançadas de memória, como Data Graph e Entity Reminiscence, melhoram a precisão ao estruturar e direcionar informações importantes.

Perguntas frequentes

Q1. O que é memória conversacional em sistemas RAG?

A. A memória conversacional ajuda os sistemas RAG a lembrar interações passadas, tornando as respostas mais relevantes e conscientes do contexto.

Q2. Por que a memória é importante nos chatbots?

R. A memória aumenta a continuidade, a personalização e a relevância nas conversas do chatbot, especialmente em interações complexas ou de várias etapas.

Q3. Qual é a diferença entre memória buffer de conversa e memória de resumo?

A. A Memória Buffer de Conversa salva todas as interações, enquanto a Memória de Resumo condensa conversas anteriores para economizar o uso de token.

This fall. Como funciona a Memória do Gráfico de Conhecimento de Conversação?

R. Ele cria um mini gráfico de conhecimento das principais entidades e seus relacionamentos, ajudando o chatbot a entender melhor as consultas complexas.

Q5. Qual técnica de memória é melhor para conversas longas?

A. A memória buffer de resumo de conversa é superb porque combina interações recentes com resumos de interações mais antigas para retenção de contexto eficiente.

A mídia mostrada neste artigo não é propriedade da Analytics Vidhya e é usada a critério do Autor.

Nibedita concluiu seu mestrado em Engenharia Química pelo IIT Kharagpur em 2014 e atualmente trabalha como Cientista de Dados Sênior. Em sua função atual, ela trabalha na construção de soluções inteligentes baseadas em ML para melhorar os processos de negócios.

Deixe um comentário

O seu endereço de e-mail não será publicado. Campos obrigatórios são marcados com *