Sentiment analysis is a common natural language processing task that involves determining the emotional tone of a piece of text. This example demonstrates how to use ControlFlow to quickly build a sentiment classifier using GPT-4o mini, showcasing the framework’s ability to create powerful NLP tools with minimal code.

Code

The following code creates a function that classifies the sentiment of a given text on a scale from 0 (very negative) to 1 (very positive). It uses a GPT-4o mini model for classification and leverages ControlFlow’s task running and result validation features.

import controlflow as cf
from controlflow.tasks.validators import between

optimist = cf.Agent(model="openai/gpt-4o-mini")

def sentiment(text: str) -> float:
    return cf.run(
        "Classify the sentiment of the text as a value between 0 and 1",
        agents=[optimist],
        result_type=float,
        result_validator=between(0, 1),
        context={"text": text},
    )

Now we can run this function on any text:

Key concepts

This implementation showcases several important ControlFlow features that enable quick development of NLP tools:

  1. Agents: We create an agent with a specific LLM model (GPT-4o mini) to perform the sentiment analysis.

    optimist = cf.Agent(model="openai/gpt-4o-mini")
    
  2. Result types: We specify result_type=float to ensure the sentiment score is returned as a float value.

  3. Result validation: The result_validator parameter is used with the between() function to ensure the result falls within the expected range.

    result_validator=between(0, 1)
    
  4. Context passing: The context parameter is used to pass the input text to the task.

    context={"text": text}
    

By leveraging these ControlFlow features, we can create a powerful sentiment classifier with just a few lines of code. This example demonstrates how ControlFlow can simplify the process of building and deploying NLP tools, making it easier for developers to incorporate advanced language processing capabilities into their applications.