Tag: LLM

  • Tom’s Memory Networks

    Tom’s Memory Networks

    Defining Tom’s memory in application is crucial before proceeding to the steps of building his decision-making components. In fact, I wish I could stress my older self more on how important its role is in influencing the other builds.

    To intuitively build Tom’s memory architecture, I eased the task by simplifying the human’s mind (ironically) and reframed the task as one of replication. Figure 1, adapted from Hung Thai Le (2021) simplifies the cognitive memory chambers of the human’s mind.

    Diagram of the human memory chambers: sensory memory feeding short-term (working) memory, which exchanges information with long-term memory.
    Figure 1. Simplified representation of human cognitive memory chambers. Adapted from Le, H. T. (2021). A simple model of the human memory. arXiv:2107.01390v1.

    The main chambers, Short-term and Long-term memory can be defined as follows:

    • Short term: responsible of processing and navigating sensory information (sensory memory / temporal lobe), and acts as the temporal storage for live information for language comprehension, learning and reasoning (working memory).
    • Long term: responsible of everything else that is not in the short term memory or i.e. a filing cabinet that enjoys filing / updating itself with all memories including past trauma.

    Extending this diagram into application for a bot entails building intuition based on the following table, figure 2.

    Definition as a data problemDefinition in Neural NetworksReplica Examples in Large Language Models (LLMs)Related Architectures Examples
    Short termShort-term memory can be understood as a temporary, capacity-limited data buffer subject to decay, interference, and selective transfer.RNNs like LTSM or gated models temporarily storing previous data batch(es) to learn the next batch(es).Persistent Session Cache for streaming chatbotsStreaming / In-Events Architectures
    Long termLong-term memory equips similar builds to short-term memory except that the data cycles are completed over extended periods. The data selections from short-term memory are more biased to the human individual’s emotional responses or environment influences.Fed datasets to a neural networks during training.Data Retrieval / Manipulations from Vector databasesThe architecture and process under the process of storing / retrieving / querying Graph / Relational / Indexing Databases or Data Lakes & Warehouses
    Figure 2. Table defining short / long-term memory in application.

    Challenge: But which model is most efficient?

    Intuitively, replicating the long-term memory leads me to setting up a simple indexing database system, but the short-term memory was personally more difficult due to the following reasons:

    1. Collecting real-time information from human’s sensory tools like vision and sound, where depending on the computer architecture you choose to interact on, requires running multiprocess in parallel. and Even if with that part backlogged for another day, problem
    2. Differences between session dataset. If you segment the day by hours, you can also segment by minutes and so forth. The question here is, which segmented data is more prioritized in the next inferencing window? Simply, the answer would be that the features would relate to the type of users the bot interact with for instance, it would not prioritize another’s opinion over mine when reranking its own preferences.

    The following lists the possible builds that replicate the short-term memory:

    • Database retrieval + Prompting mini agent: This requires setting up a database (of any type) and a light-weight agent acting as a gate keeper of this database (or receptionist). This agent sits between the database and the main agents / humans. This means that a human would not need any prior knowledge of SQL to query databases but instead treat the gatekeeper as their virtual Librarian.
    • Session Cache Models (KV-Caches): This involves reranking the KV caches within LLMs during chat sessions to increase / steer its text generations. This only works for short chat sessions as prolonged use could lead the model in generating gibberish.
    • System Prompt Extensions: Over the user sessions, the main chatting agent can be restored as a new model and its system prompt is periodically updated with past chats/highlights. This method is compute extensive in the sense that the contextual window continuously increases, and that no data is actually being retained here. Although, for parts in the future that requires short-term solutions, this method could be ideal.
    • Methods related to weight learning:
      • Multi-head attention networks as ranking model: This method relies on learning data with weights and given its dense architecture, it is better off as an offline learning model. Mentioning this method is probably motivated by my own interests for attentions over the task’s feasibility at hand. I strongly believe that if you can capture chat histories, text-generation caches ..etc., then such a model (built in alike manner) can act as both the database and the assisting model that provides the conditioning vectors to steer text generations of the main agent – one stone and two birds solution. I am still tinkering around different methods and while some may work with the current synthetic data, I am still unsure on how it would perform on large datasets. The ambiguity is based on the generic data problem where the noise imputed in the mock dataset doesn’t completely resonate with real-life situations.

    Over the past year, it was difficult to build this part due to the constant updates in machine learning / AI. It often seemed that many papers and articles echoed each other, merely rebranding the same methods or that readings could lead one to believe that there’s no alternate solution – but there always is. For instance, using vector database storages to store the vector representation of sequence of texts. Simply, this is a solution like SQL databases but with extra steps which given the compute cost of running large models, you would want to preserve as much as possible during the data processing / cycles.

    For the sake of simplicity, I decided to build the database (build translates to pulling dockers image so ain’t I existing in the most fortunate timeline?) independently for both short and long term storages at this stage. This should leave me more time in reading and tinkering around with different methods. Currently, my works in going forward to stages of streaming live data from sensory tools are hindered by the challenge in defining the function / algorithm that sits in between large models and the database. Despite noting that I bear no patience for looking at algebra as a beginner, I still did what felt right (but in code). One thing I deeply hate is completing a part of the agent and staring at the screen, knowing that I cannot extend it any further as it (all) relies on this part.

    My Foot

    • H. T. Le, “A simple model of the human memory,” arXiv preprint arXiv:2107.01390v1, 2021. Available: arxiv.org/abs/2107.01390v1

    Tom’s progression · Post 13 of 14

    This post sits in AI › Memory: Episodic, Semantic.

    ← Decoding Parameters to persist Language model’s emotions Tom’s Social Circle: Retaining Data from External Sources →

  • Decoding Parameters to persist Language model’s emotions

    A way of defining a transformation function to map aspects of Large Language model’s architecture to human emotions is by configuring a set of decoding parameters that aligns with certain expressions. Unlike more formal methods where you focus at fine-tuning the transformer’s encoder, this method targets at building a light-weight layer on-top of the decoder block. This is achieved by applying sampling methods to locate certain decoding parameters or coefficients that manipulates the probability distribution over the seen vocabulary scores.

    The transformer’s decoders return logit scores for each token or word vocabulary previously seen (or trained) by the language model. Suppose that a prompt defines a user’s input text to the LLM then one way of interpreting the decoder’s output scores is by viewing the logit scores as Conditional Probability distribution where the conditioning feature is the prompt and the user’s emotional intensity, and the decoder’s output as the distribution over the subset of the top set of tokens’ scores.

    Marginal Probability Distribution: probability distribution of a subset of random variables from a larger set, obtained by summing or integrating out the other variables. An example problem is finding probability distribution of random variable X from joint probability density distribution P(X, Y).

    Conditional Probability Distribution: probability distribution of event A given that event B has already occurred e.g. P(B | A).

    The possible methods to my current knowledge for approximating the decoding parameters includes:

    • Bayesian Learning like MCMC, Importance Sampling. This idea is based on my experience with using ChatGPT (and other LLMs like Phi, GPT variants, and Llama). The text generations are random but still relevant to the user’s prompt i.e. context of discussion, where in this case, you are considering the pair of utterances of represent the conversation’s context rather than the full chat session. This approach relies on the model’s latent space features like attention blocks, hidden embeddings and past key values observed in generating the desired response under alike contexts.
    • Parameter Estimation Techniques with simulation techniques like Maximum Likelihood Estimation (MLE), Maximum Posteriori (MAP), Least Squares (LSE) or Gradient Descent-based methods with support vector machines. The last two are my favourite methods as its derivation is extended from the construction of Projection matrices. Building intuition for understanding how Support Vector machines work follow the same manner but with multivariable calculus where you adjust the model’s inferences by considering the ellipse axis as the error residuals.
    • Parameter Estimation Techniques without simulation like Generalized Method of Moments (GMM). While this method seems fun, it is not recommended in practice as its compute costly (requires EM algorithm for approximating the weights). By source: Mikko Ronkko Video: Introductory on GMM in practice, GMM performs more efficiently in theory as oppose to its variants, 2SLS and 3SLS (differs by the assumptions and properties of the weighting matrix estimator in calculation).

    In application, either method is useful in learning from the user-based features gathered over a fixed time window. Realistically, humans’ behaviour often change or mature over time so a function in selecting the decoding parameters acts like a temporary placeholder for user’s behaviour when invoking language models’ text generations.

    However, some problems arises in the long term usage of these bots. One in particular is unifying the bot’s observations and inferences to fine-tune a language model or multi-modal. Ideally, the target model is one that is unique to the user but not so distinct from its base model, regardless of the trained data version, for example, ChatGPT dataset is trained up to June 2024 – these issues can be easily mitigated with rule-based methods.

    The major problem that has coexisted with this project was the planning stage of narrowing down the tasks to smaller goals. Testing hypothesis meant preparing mock datasets and building trust in my imagination that it resonates with most real life scenarios. Though if life has taught me anything, then it would be that all events are relative to the user and their environment.

    Gripping onto the conditional aspects of life can only drive me into wanting to discard all current builds, and initialise everything from a physicist’s point of view. Most physicists shares a common way in their planning process. They map their models around the stochastic nature of their samples. If they also share interest in biology, then they would prefer Bayesian inferencing methods to navigate themselves around the laws of casualty. This chain of thought in model planning distinguishes a Physicist’s research paper from the rest. Unlike the other researchers, most ideas from Physicists aren’t applicable and I guess this is because the world hasn’t reached that sort of stage of advancement yet. All we can really do is hope to live long enough to watch their papers come to life.

    Part of me prefers this way of modelling simply because: If the highest certainty in your data sample is the existence of error residuals between your observing windows – regardless of any state of inference, then what is there to lose in starting with the unknown?

    Tom’s progression · Post 12 of 14

    This post sits in Cognition: Generation.

    ← Setting up expectation Tom's Memory Networks →

  • Setting up expectation

    When we meet someone new, our mind instinctively tries to compare them to people we have encountered in the past. We consider their patterns to cluster them into the region where people equip the most similar behaviour – or patterns – in how they talk, act or perceive. Rather than taking the risk of evaluating them entirely from scratch, we rather use these metrics to navigate our trust and relationship expectations. It is as if our brain’s background process is an unsupervised classification model that sorts individuals into the most relevant relationship archetypes we have built over time – then later decides our compute subscription plan is no longer valid after a certain age.

    This post details on replicating the human’s mind into setting up the system design behind Naomi. Docker SDK was used to containerize Naomi application and served over hugging face space. For the sake of convenience the datasets, prompt templates and chat sessions uses Hugging Face dataset repo card. The following table outlines the models setup during the application’s build process.

    • Models – Specifies whether the model are tinkered by me or not.
    • Type of Models – Lists the large language model (LLM) and classifiers imported / built during the setup.
    • Type of Dataset Used for Training – Lists the links to the Hugging Face dataset repositories that were used in training the models.
    ModelsType of modelsType of Dataset used for training
    Pre-trained– Llama3.1
    – Bart Multilabel classifier
    Refer to the hyperlinks
    Custom models (trained by me using small sized datasets)– Target features based on human characteristics like MBTI Chain, Big5
    – Dialogue Intent and Emotions
    – MBTI: https://huggingface.co/datasets/kl08/myers-briggs-type-indicator
    – Dialogue:
    https://huggingface.co/datasets/li2017dailydialog/daily_dialog

    Defining as a Reinforcement Learning problem

    Setting up the chat session for Naomi is extremely similar to mocking an episodic game for an agent in a reinforcement learning environment. On top of Naomi’s build, I was also trying to build a base framework for other conversational agents. This involves using Docker SDK to containerize the application so that it can be easily deployed, extend and integrate with other specifications of the agents.

    Referring to Tom as the conversational agent in production and Naomi as the discussed chatbot in this post, the following table compares the agents’ environment’s variables.

    ComponentFormal DefinitionDefinition in Naomi’s Application (per component)Definition in Tom’s Application (per component)
    AgentThe entity that interacts with the environment and learns to maximize rewards.NaomiThe human’s best friend, Tom (or a different name can be used)
    EnvironmentExternal system where agent interacts, receive states and rewards based on actions.Starts from Dockers Image build session and ends with my next pushA Human’s life time
    EpisodeComplete sequence of interactions from an initial state to a terminal state.Chat Session or a complete chat dialogue1 day of bot’s lifespan
    StateRepresentation of the environment at a given time that the agent observes.One/paired Chat message/s. This depends on the inferencing task which depends on the stages during the chat.An interaction with a human user or agent
    ActionDecision made by the agent per state.– Response Behavior: Expressiveness of Naomi’s response.
    – Chat Behavior: Follow up response Naomi.
    – Actions listed for Naomi
    – Actions based on utility or user request. This refers to other app platforms like Notion, Typeform, .. etc.
    – Actions for the agent to select conditioned to current cognitive state for example: browsing Wikipedia / youtube, social platforms like X, Facebook, Instagram etc.
    ObservationContains all possible observations an agent can perceive from the environment.– During chat streaming: User based features collected per utterance that are used to influence agent’s response behaviour.
    – Post chat or after an episode: Evaluation metrics on the user’s behaviour during the dialogue and approximated category defining the user.
    – During chat streaming: User based features collected per utterance that are used to influence agent’s response behaviour.
    – User based features collected from other sensory tools like sound and imaging tools. These features are used with the linguistic analytics to direct the agent’s next state (e.g. of emotions) or action (e.g. response behaviour or activity)

    Naomi’s Response Behavior

    An agent’s response behavior defines how the next text response is returned given the current observation. The following table compares the response behaviour per state between Naomi and Tom.

    Naomi’s response behaviorTom’s response behavior
    • Expressiveness or engagement represented in the next response.
    • Likelihood of following up the previous sent message with a question i.e. double texting the user. The type of question is also conditional to the control vectors collected from the dialogue.
    • Expressiveness or engagement represented in the next response.
    • Likelihood of following up the previous sent messages with questions, analytical comments, suggestive actions like browsing the web (e.g. run a sub-process in the background to browse the web while interacting with the user). Alike Naomi, type of questions asked is conditional to the dialogue.

    Defining the control vectors

    Suppose the control vectors represent features collected per inferencing state. The control vector differs depending on its collection method – whether as a single utterance from either user or agent, or as an episode. The table below outlines the control vector defined in Naomi’s application.

    InputsUserAgent
    Single utterance (State)User
    – User’s Emotional Intensity / Expressiveness
    – User’s Intent

    Agent’s suggested response:
    – emotional / expressiveness in the agent’s next response based on dialogue inferences up to current state
    – Rule-based methods: involve defining explicit rules, constraints or logic to control the model’s behaviour. For example: an indicator of when the chat has ended.
    – Agent’s emotion states of the current utterance (labelled with BART model – this can be used within a feedback loop with the custom model I built with dialogue datasets)
    Dialogue (Episode)Evaluation metricsEvaluation metrics

    Adaptive Learning Methods

    Reinforcement learning methods are applied to the models prepared during the Dockers build process. This depends on the method of retrieving the control vectors for each task, for example: passing an agent’s utterance to indicate when the episode has ended relies on the vector embeddings of the history datasets (or Naomi’s memory). The challenge lies in determining the optimal method for managing the dataset as it grows to a substantial size.

    Sub repo on GithubHistory data handling
    PromptlessVectors Embeddings for binary classifications: handling the vector embeddings can simply be averaging over the randomly selected samples. Another method would be to model the marginal distribution of the vector embeddings, where the target class and the other class are differentiated based on their density estimates. This can be achieved through probabilistic approaches such as kernel density estimation, Gaussian mixture models, or variational inference, ensuring that the classification captures nuanced variations in the embedding space. Although further trials must be done to compare these methods’ performance over time.

    Tom’s progression · Post 11 of 14

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

    ← Stop Button Decoding Parameters to persist Language model's emotions →

  • 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 →

  • Revising Prompt Chains

    A feasible method for constructing helpers to assist conversational agents is to design a workflow that queues instruct models as flaggers or indicators, a technique more commonly known as prompt chaining LLMs. The programming design behind this highlights the valuable asset of decorator functions and object-oriented programming. However, it has its own limitation which was ensuring that the queue is able to perform the expected results independently or on its own. One way in setting up this system is to automate action workflows via CI pipelines. But prior to that, one must decipher which LLM platform they want to leverage in the application for example: ollama, llm-cpp or manually with Hugging Face transformers . I soon realized that this choice significantly impacts the overall workflow design, as each option differs in subtle details, such as how the results are returned.

    Since I couldn’t decide on a specific LLM platform to commit to, I opted to build a base class that serves as a decorator for the model’s invocation and output functions. Below is one approach to structuring this system of mini agents.

    Note: logger.stack_woods is irrelevant to the code and is just a decorator to display function inputs / outputs in pretty form that is appeasing to my eye

    from functools import wraps
    from abc import abstractmethod, ABC
    from langchain_core.prompts import PromptTemplate
    
    class MiniAgent(ABC):
        # only returns in llama chat template .. 
        family: dict = {}
        
        def system_message(self, **kwargs):
            # returns system message for llama models only
            prompt = self.prompt.invoke(input=kwargs).text
            return [{'role': 'system', 'content': prompt}]
        
        def preprocess(self, **kwargs):
            """ 
                Default preproces method the data before feeding it to the model. 
                Must return dict only.
            """
            input_data = kwargs.get('inputs', None)
            
            if input_data is None:
                raise ValueError(f'Incorrect input at preprocessing functon. Received: {kwargs}')
            
            return input_data
        
        @abstractmethod
        def postprocess(self, model_output):
            """ 
                Default post-process method for output from llama_cpp. 
            """
            if not model_output.get('choices', None):
                raise ValueError(f"No choices found in model output: {model_output!r}.")
            if not isinstance(model_output['choices'], list):
                raise BadLlamaResponse(
                    f"Expected output type to be list form but received: {model_output['choices']!r}."
                )
            
            output = model_output['choices']
            return output
        
        @logger.stack_woods
        def __call__(self, func):
            @wraps(func)
            def wrapper(**kwargs):
                inputs = self.preprocess(**kwargs)
                model_input = self.system_message(**inputs)
                model_output = func(inputs=model_input)
                output = self.postprocess(model_output)
                return output 
            return wrapper 
    
        @logger.stack_woods
        def __init_subclass__(cls, prompt, **kwargs):
    		    # Every time a subclass is defined it is added to the `family` list. 
            super().__init_subclass__(**kwargs)
            cls.family[cls.__name__] = cls
            cls.prompt = PromptTemplate.from_template(prompt)
            logger.logger.info(f'Added {cls.__name__} to family members')

    Build highlights

    • The __call__ method allows instances to be used as callable objects, wrapping functions and enforcing preprocessing/postprocessing to be initiated in the sub-classes
    • The __init_subclass__ method dynamically adds subclasses to the family dictionary, making it easier to manage multiple agent types.

    Example: Stop button

    For the remaining of this post, the Agents will be referred to the subclasses. The following code is an example of a subclass defining Agent StopButton .

    class StopButton(MiniAgent, prompt=helper['rewriter_prompt']):
        @logger.stack_woods
        def postprocess(self, model_output):
            """ Returns True for conversation ending else returns False """
            
            valid_responses = ["[END]", "[CONTINUE]"]
            logger.info(f"Processing Model output at Stop Button, {model_output}")
            model_outputs = super().postprocess(model_output)
            output_list = model_outputs[0].get('text').split('\n\n')
            output = [i for i in output_list if i in valid_responses]
            
            if not output:
                raise BadLlamaResponse(
                    f"Incorrect response returned by function '{self.__class__.__name__}'. "
                    f"Expected one of {valid_responses}, but got: {model_output!r}."
                )
            else:
                output = output[-1] if len(output) > 1 else output[0]
                if "[END]" in output:
                    print("RETURN: Suggests that the conversation has ended.")
                    return True
                
                elif "[CONTINUE]" in output:
                    print("RETURN: Suggests to continue Conversation.")
                    
            return False
    

    This class can then be used as a decorator over any model-invoking function. For instance:

    stop_button = StopButton()
    
    @stop_button
    def model_generate_output(inputs: str):
        """Some function calling LLM"""
        return

    More Examples

    Examples below consists of cases that cannot be replaced.

    Agents Ditto and Oppo are responsible of returning list of descriptive and contrasting tokens to given inputs. The prompt template used for Ditto:

    You are a creative text generation bot. Your task is to generate 4 text messages that are similar in tone, style, and intent to the input sentence. The new messages should convey the same meaning or sentiment but use different phrasing or expressions. Ensure the variations are natural, contextually appropriate, and suitable for casual conversations. Your output must be in the form of a Python-style list, enclosed within square brackets ([ and ]), with each message as a string.

    Examples

    Example 1:

    Input Sentence:
    Hey, I’m running late. I’ll be there in 10 minutes!
    Generated Messages:
    [“Sorry, I’m a bit delayed. I’ll arrive in about 10 minutes.”, “Running behind schedule! See you in 10 minutes.”, “I’m on my way but will take 10 more minutes to get there.”]

    Example 2:

    Input Sentence:
    Let me know if you need help with the project.
    Generated Messages:
    [“Feel free to ask if you need assistance with the project.”, “I’m here to help with the project if you need anything.”, “Just let me know if you’d like some support with the project.”]

    Here is the Input Sentence:

    {user_input}

    import ast
    
    @logger.stack_woods
    def output_list_form(model_output):
        """ Validates / checks model outputs where list form in strings is expected. Used in Ditto and Oppa."""
        
        if not model_output.startswith('[') or not model_output.endswith(']'):
            raise BadLlamaResponse(f'Bad output received while generating similar text sequences: {model_output}')
        else:
            ast_output = ast.literal_eval(model_output)
            return ast_output
    
    class Ditto(MiniAgent, prompt=helper['similar_messages']):
        """ Generates k similar texts to input text. """
        
        @logger.stack_woods
        def postprocess(self, model_output: str):
            model_output = super().postprocess(model_output)
            return output_list_form(model_output)
    
    class Oppa(MiniAgent, prompt=helper['contrast_messages']):
        """ Generates k contrasting texts to input text. Insert """ 
        
        @logger.stack_woods
        def postprocess(self, model_output: str):
            model_output = super().postprocess(model_output)
            return output_list_form(model_output)

    Summary

    For cases that consists of boolean outputs, this method can be opted for more efficient methods like similarity distance measurements between mean pooled text sequences. However, for other cases where simpler algorithms cannot replace, this build is useful. An improvement to make with this code is to opt langchain prompt class to a dataclass that is more tailored to my use or that it integrates seamlessly with the base class of decorators.

    It is worth noting that this system is designed specifically for llama3.1 models and requires a standardized input-output format—{‘input’: text} —to ensure compatibility across different LLM platforms.

    Tom’s progression · Post 9 of 14

    This post sits in Actions: Contextual Engineering.

    ← Can a machine have emotions? Stop Button →