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 →

discussion

Leave a Reply