Stop Button

This post briefs on methods on developing pipelines to assist conversational agents during live interactions. One way to conceptualize this pipeline is as a queue of flaggers or indicators. A key indicator in this setup is a mini-agent responsible for continuing or ending the chat, referred to as StopButton.

Trialed Methods

Brainstorming ways to implement StopButton led to the following approaches

  1. Prompt-Chain: Invoking a queue of prompting-instruct language models, specifically llama3.1. More details can be found in here.
  2. Vector Embedding: Leveraging contextual information within text sequence embeddings and comparing it against incoming data.

The table below summarises the pros and cons for relying on the fore mentioned methods.

Method ProsCons
Prompt-chain– Easy setup– Compute inefficient, especially in returning boolean statements
– The first problem can be mitigated with quantized models. However, the smaller the language model, it is more likely for the model to fail returning expected results
Vector Embedding– Faster
– Less compute cost compared to invoking an LLM
– Contextual embeddings is relative to the type of data that was fed to the pre-trained models. As a result, it is not domain specific. If one is eager to customize some layer that adapts to the user’s preferences i.e. minimizes / maximizes the distances of text embeddings, you can refer to this post here – If this method sounds too tiresome to setup or for whatever reason, then a separate and weightless model can be used accustom to the streaming / unseen dataset.

The main flaw in utilizing method 1 is that language models are not always consistent with its results. When considering possible problems in applying large language models (LLM’s), I like to imagine some counting process behind the models’ response generation where its first success is when the model fails to return the expected results. Another way of perceiving LLMs is referring to the concept of Central Limit theorem, where regardless of the initial or sampling distribution, the sample mean will tend to follow a normal distribution. Without considering the model’s cache per session, the model is destined to make mistakes and ultimately ends up at some Normality relative to their “stupid state”—i.e., generating incorrect responses. This problem is particularly prominent in compressed LLMs.

Vector Embeddings Evaluation Metrics

The most common method in comparing vector embeddings is cosine distance similarity. Other comparison metrics include dot product, manhatten andeuclidean distances . The following lists the trialed methods for comparing vector embeddings. The text sequences are encoded using sentence_transformers with pre-trained model all-MiniLM-L6-v2 , which has the smallest embedding size (384 dimensions) according to my current knowledge.

  1. Cosine Distance Metric: the target and contrast corpus embeddings are stored and used to compare incomming messages. Cosine distance is then applied to pairs of embeddings to compute similarity scores.
  2. Dimensional Reduction: methods like PCA where the ideas of analysis were scoped from methods found in Auto-encoders.
    1. Reconstruction Error: Fitting PCA from scikit-learn to the target corpus and evaluating the reconstruction error using Mean Squared Error (MSE). The fitted PCA model is then used to reconstruct new (unseen) data, with MSE serving as the evaluation metric.
    2. [Do not try] Noise as Reconstruction Error: alike the popular method used with AutoEncoders in fraud detection, the similarity of the target corpus against incoming data can be deduced by reflecting on the differences of noise existing in both datasets. The task here can be sculpted as: Retaining a fixed number of components (e.g. 95% of the total variance in the dataset), the goal is to infer the noise or information lost due to dimensionality reduction. This is the same objective suggested in the previous point but differs in how the code is setup. This is accomplished by concatenating the new data with the target corpus and comparing the compression-induced noise loss against that of the target’s compressed embeddings – this method shouldn’t ever be considered as its highly sensitive to the precision of the floating points but I thought the programming part seemed cool. It is bad in the sense that it doesn’t capture true intrinsic information for the purpose of this task and that it requires more operations than necessary. Still, it deserves its place here in the post to remind myself to not do this again.
Stop Button Build

While constructing these chatting agents, the final system used in application I had in mind behaves like a context manager. In saying that, the incoming pair of chat messages from user and agent are passed per message sent by the user.

Narrowing the task down to defining the type of inputs:

  • Pair of utterances from user and agent:
    • Problem: The problem with relying on this system is that it can be easily hijacked with a user sending [END] or the key words to ending a conversation. This raises issues in saving incomplete dialogues as completed chats.
    • Solutions:
      • Setup another workflow e.g. PeriodicCacher process that is invoked asynchronously to the chat and StopButton . It is fed with chunks of chat dialogue for e.g. the last 5 pair of speeches, and returns the likelihood of the chat coming to an end or [END] is approaching. The model is partial fit per chat window dialogue and processed by chunking chat messages i.e. 1 batch of dataset equates to 1 chunk of chat messages.
      • Refer to the following technique where one utterance is only considered.
  • One utterance from the agent only:
    • Problem: if any farewell messages are returned from the agent – whether as a joke or part of some explanation, StopButton can still categorize this as a farewell message.
    • Solutions:
      • When initiating the target corpus, only specify the certain ending terms for example, ‘[END]’ . Note that this would require the conversational agent to return the special token as part of its dialogue script.

I’ve settled with the second option and built a small CLI plugin that is devoted to utilizing vector embeddings as flaggers: promptless. To extend StopButton’s current build, I would like to add a certainty metric that is able to assist the model’s adaptation to unseen dataset. However, prior to this setup I must complete the build behind the Agent’s observational space – streaming pipelines of user-based features gathered in real-time. This is particularly important in building the Agent’s intent in returning second responses or analytical questions. Referring this segment as a separate python module, I would like to target at building it separately to other existing components as much as possible, as I have a hunch that its completed build will not be my last and would require more tries.

In applications, I guess defining an agent’s observational space can be difficult because it depends on other system components, but those components also need to be designed with the observational space in mind. Somewhat like a chicken-and-egg problem where you have to iteratively refine both sides. This emerging problem isn’t surprising given that the primary features donor is the human user. Though, I should follow my hunches in relying on the human user’s behaviour as my guiding light in building these agents. If data cannot be used as insightful features, then it can be used as a negating feature. Every kind of dataset is useful, regardless of its quality, size or its poor preprocessing pipelines.

Anyway, building a linear layer to adapt to new data can be like the following code (the optimizer is SGD for the perfectionist and Adams for the lazy ones):

import torch
import torch.nn as nn
INPUT_DIM = 384
HIDDEN_DIM = 150
MODEL_CARD = "sentence-transformers/all-MiniLM-L6-v2"
device = (
"mps"
if torch.backends.mps.is_available()
else "cuda"
if torch.cuda.is_available()
else "cpu"
)
class DistanceModel(nn.Module):
def __init__(self, input_dim = INPUT_DIM, output_dim = HIDDEN_DIM):
super(DistanceModel, self).__init__()
self.f = nn.Linear(input_dim, output_dim)
self.relu = nn.ReLU()
self.loss_fn = nn.CosineEmbeddingLoss()
self.to(device)
# self.optim = torch.optim.Adam(self.parameters(), lr)
def forward(self, input1, input2, target=None):
"""
Computes cosine similarity-based loss.
:param input1: First input tensor (batch_size, input_dim)
:param input2: Second input tensor (batch_size, input_dim)
:param target: Label tensor (-1 or 1) for similarity
:return: Transformed features and loss value
"""
x1 = self.relu(self.f(input1)).to(device)
x2 = self.relu(self.f(input2)).to(device)
# Compute cosine embedding loss
if target is None:
loss_value = None
else:
loss_value = self.loss_fn(x1, x2, target).to(device)
print(
f"X1 shape: {x1.shape}, X2 shape: {x2.shape}, Loss: {loss_value.item()}"
)
return x1, x2, loss_value

Tom’s progression · Post 10 of 14

This post sits in Cognition: Executive functions · Actions: Tool & Skill Capabilities.

← Revising Prompt Chains Setting up expectation →

discussion

Leave a Reply