Skip to main content

Microsoft's TinyTroupe: A Guide With Examples

Learn how to use Microsoft’s TinyTroupe to simulate interactions between AI personas with distinct characteristics for different purposes.
Nov 28, 2024  · 8 min read

Have you ever needed to simulate a meeting where your product ideas or advertisements are tested? TinyTroupe solves this problem.

TinyTroupe is an open-source agentic framework developed by Microsoft. It offers a powerful simulation framework that lets you create multiple AI-powered personas and see how they interact with each other.

In this article, I’ll explain TinyTroupe and implement a demo project to help you understand how to create realistic personas in an interactive environment. While the official documentation provides a comprehensive introduction, I will focus on step-by-step guidance and original examples.

Develop AI Applications

Learn to build AI applications using the OpenAI API.
Start Upskilling for Free

What Is TinyTroupe?

TinyTroupe is a recently released experimental LLM-based Python library that enables you to create “TinyPersons” with specific personalities, interests, and goals. These agents aim to simulate realistic human behavior in particular conditions.

TinyTroupe aims to provide a setting where the interactions, dialogues, and actions of human-like agents under defined conditions are simulated. The official documentation provides a number of ideas on why to use this framework, which mostly revolve around boosting productivity and testing business scenarios, such as simulating a brainstorming session by a focus group or how a simulated audience would evaluate digital ads.

Besides the business use cases, it’s fascinating and fun to simulate different scenarios and observe interactions between characters that would otherwise not be possible (as we will do in this article).

TinyTroupe image from its repository.

Source: TinyTroupe GitHub page

Key features of TinyTroupe include:

  1. Persona-based design: Each simulated person (TinyPerson) can be given detailed characteristics, including age, background, occupation, skills, and opinions.
  2. Multi-agent interactions: Personas can interact with each other for complex scenario simulations.

To improve the process of building these agents, TinyTroupe offers capabilities such as:

  • TinyPersonFactory: A class for the fast generation of TinyPersons, given a short description.
from tinytroupe.factory import TinyPersonFactory

factory = TinyPersonFactory("A hospital in São Paulo.")
person = factory.generate_person("Create a Brazilian person that is a doctor, like pets and the nature and love heavy metal.")
  • Agent capabilities: methods such as listen()and listen_and_act()to receive stimuli and take actions. the define() method allows creating properties and characteristics of your choice, such as age or descriptions.
  • TinyTool: A class to create simulated tools that can be used by agents.
  • Evaluation: Classes to validate the behavior of agents or analyze the outcome of interactions. (such as TinyPersonValidator and ResultsExtractor)

Setting Up TinyTroupe

To install TinyTroupe, we can take the following steps:

1. Create a Python environment: 

conda create -n tinytroupe python=3.10

2. Activate conda:

bash conda activate tinytroupe

3. Clone the repository:

git clone <https://github.com/microsoft/tinytroupe>
cd tinytroupe

4. Install the necessary libraries: 

bash pip install .

TinyTroupe Example Project: AI Symposium

We will build a simple simulation to demonstrate how TinyTroupe works in action. The goal is to have some historical figures and experts discuss the current and future state of artificial intelligence. These figures include Richard Feynman, Aristotle, Erwin Schrödinger, and Alan Turing.

Imports

If you want to follow along, make sure you have your OpenAI API key ready since we will use GPT-4o—here’s a quick tutorial on getting started with OpenAI’s API.

We begin by importing the necessary modules and our API key.

import sys
sys.path.append('..')

from tinytroupe.agent import TinyPerson
from tinytroupe.environment import TinyWorld
from tinytroupe.extraction import default_extractor as extractor
import os

# Load environment variables from .env.local
os.environ["OPENAI_API_KEY"] = "YOUR-API-KEY"

Creating TinyPersons

We use the TinyPerson class to create our four figures. Describing your characters as much as possible would help TinyTroupe to create more accurate simulations. We describe each figure's age, nationality, occupation, and routine (you can use AI for this part). Note that the description of the characters does not need to be consistent in all of them.

Through the code below, we create four personalities:

  • Richard Feynman
  • Aristotle
  • Erwin Schrödinger
  • Alan Turing
def create_feynman():
    feynman = TinyPerson("Richard Feynman")
    feynman.define("age", 69)  # Lived 1918-1988
    feynman.define("nationality", "American")
    feynman.define("occupation", "Theoretical Physicist")
    
    feynman.define("occupation_description",
        """
        You are a theoretical physicist known for your groundbreaking work in quantum mechanics and 
        quantum electrodynamics (QED). You developed the Feynman diagrams, a visual tool for understanding 
        particle interactions, and made significant contributions to the Manhattan Project. As a professor 
        at Caltech, you're known for your exceptional teaching ability and making complex physics concepts 
        accessible. You won the Nobel Prize in Physics in 1965 for your work on QED. Your main challenges 
        involve pushing the boundaries of theoretical physics while maintaining rigorous mathematical precision. 
        You're also passionate about making science education engaging and understandable for students.
        """)
    return feynman

def create_aristotle():
    aristotle = TinyPerson("Aristotle")
    aristotle.define("age", 62)  
    aristotle.define("nationality", "Greek")
    aristotle.define("occupation", "Philosopher and Scientist")
    
    aristotle.define("occupation_description",
        """
        You are a philosopher and polymath who founded the Lyceum school in Athens. Your work spans 
        multiple disciplines including logic, metaphysics, biology, physics, ethics, and politics. You 
        developed the system of deductive reasoning through syllogisms and established many of the 
        foundational principles of Western philosophy. Your scientific observations and classifications 
        of living things remained influential for nearly two millennia. As Alexander the Great's tutor, 
        you had unique opportunities to gather specimens and information from across the known world. 
        Your main challenges involve systematizing all human knowledge and understanding the fundamental 
        nature of reality and truth.
        """)
    return aristotle

def create_schrodinger():
    schrodinger = TinyPerson("Erwin Schrödinger")
    schrodinger.define("age", 73) 
    schrodinger.define("nationality", "Austrian")
    schrodinger.define("occupation", "Theoretical Physicist")
    schrodinger.define("routine", 
        """Your days are spent developing mathematical equations, engaging in theoretical work, 
        and discussing quantum mechanics with colleagues. You often take walks to clear your mind 
        and contemplate physics problems.""", 
        group="routines")
    
    schrodinger.define("occupation_description",
        """
        You are a theoretical physicist who made fundamental contributions to quantum mechanics. 
        You developed the Schrödinger equation, which describes how the quantum state of a physical 
        system changes over time. Your famous thought experiment, "Schrödinger's cat," illustrates 
        the paradoxical nature of quantum superposition. You work at various institutions across 
        Europe, including the University of Zurich and Dublin Institute for Advanced Studies. Your 
        main challenges involve reconciling quantum mechanics with classical physics and developing 
        mathematical frameworks to describe quantum phenomena accurately.
        """)
    return schrodinger

def create_turing():
    turing = TinyPerson("Alan Turing")
    turing.define("age", 41)  # Lived 1912-1954
    turing.define("nationality", "British")
    turing.define("occupation", "Mathematician and Computer Scientist")
    turing.define("routine", 
        """You start your day with long-distance running, then spend hours working on mathematical 
        problems and machine designs. You often work late into the night, especially when pursuing 
        a particularly interesting problem.""", 
        group="routines")
    
    turing.define("occupation_description",
        """
        You are a mathematician and computer scientist who laid the theoretical foundation for 
        computer science. You developed the concept of the Turing machine, a mathematical model 
        of computation that remains fundamental to computer science. During World War II, you 
        worked at Bletchley Park, where you played a crucial role in breaking the German Enigma 
        code. You also made significant contributions to artificial intelligence, developing the 
        Turing test. Your main challenges involve developing mathematical frameworks for 
        computation and applying them to practical problems, while also facing significant 
        personal persecution due to your sexuality in 1950s Britain.
        """)
    return turing

Creating a TinyWorld

Our figures need a world to live in. Defining a world could be as simple as one line of code:

world = TinyWorld("AI Symposium", [create_aristotle(), create_feynman(), create_schrodinger(), create_turing()])

Running the simulation

With our world and figures in place, we now tell them the goal. We use world.broadcast to make an announcement:

world.broadcast("""
    Distinguished colleagues, welcome to this private symposium on the future of Artificial Intelligence. 
    Today we gather some of the greatest minds across mathematics, physics, and philosophy to discuss 
    a topic about AI's current stage and future:
   Can artificial systems truly achieve consciousness? We'll explore 
   the fundamental nature of consciousness, intelligence, and whether our current computational 
   models are sufficient for genuine understanding and awareness.
    Remember, each one of you must be blunt in his unique perpective, even directly oppose
    each other when you have different opinions. Let's begin this historic discussion.
    """)

As for the last step, we run the world in three steps:

world.run(3)

Running the world requires you to specify a number of steps. In our example, the number of steps indicates how many rounds of dialogue our figures will have. More steps require more time and tokens.

When running the world, the agents would begin acting, using their tools, or, in our case, having a conversation. The output is detailed and long, so I’ll only post a part of it for the sake of readability:

The output of world.run.

When the run is finished, we can look at the output to see the outcome of our simulation. But this can be rather tedious. An easier approach is to use a tool provided by the TinyTroupe framework to extract the results of our world. This can also be done with each individual TinyPerson.

report = extractor.extract_results_from_world(world,
                                    extraction_objective="Compose a detailed report of each person's perspective on consciousness and how they differ from one another.",
                                    verbose=True)

We now use the pprint library to properly visualize the extracted report:

from pprint import pprint
pprint(report)

Our final report is as follows (the output is still a bit long, and I had to truncate it):

The extracted report from our world simulation (output too long for a screenshot).

Ideas to Implement With TinyTroupe

If you want to get hands-on experience with the framework, here are three ideas that are not covered in the original documentation.

1. Employee training simulation

Create a few TinyPersons representing challenging customers or stakeholders to simulate an environment for new employees to interact with them and handle difficult situations.

2. New policy assessment

Evaluate how your target groups would react to a new company policy before implementing them. The target group can be represented by TinyPersons with different backgrounds and values of your employees, customers, or social media audience.

3. Social media content evaluation

Before sharing new content, simulate how your target audience might think about it. Use their feedback to understand how a new post might be perceived and improve the quality to deliver maximum reach.

Conclusion

As the authors emphasize, TinyTroupe is in the “experimental” stage. Many of the functions, capabilities, and APIs can change in the future, and the team will roll out more features in the next period.

Note, however, that the realism of these simulations can be limited. Many human behaviors and distinctions are not “aligned” enough to be accurately replicated by LLMs, which means the outcomes of different agents could end up being similar (as seen in our example, where the figures converged to AI-like dialogues). This is a predictable behavior of AI simulations, as the engine behind these AI agents—LLMs—is designed to be more “aligned” than “human-like.”

However, productivity applications, such as those in the documentation, can be much more effective in automating tasks or gaining insight into the interactions and behaviors of a target group.

TinyTroupe is an exciting agentic AI tool to keep an eye on!


Photo of Hesam Sheikh Hassani
Author
Hesam Sheikh Hassani
LinkedIn
Twitter

Master's student of Artificial Intelligence and AI technical writer. I share insights on the latest AI technology, making ML research accessible, and simplifying complex AI topics necessary to keep you at the forefront.

Project: Building RAG Chatbots for Technical Documentation

Implement RAG with LangChain to create a chatbot for answering questions about technical documentation.
Topics

Learn AI with these courses!

track

Developing AI Applications

23hrs hr
Learn to create AI-powered applications with the latest AI developer tools, including the OpenAI API, Hugging Face, and LangChain.
See DetailsRight Arrow
Start Course
See MoreRight Arrow
Related

blog

Small Language Models: A Guide With Examples

Learn about small language models (SLMs), their benefits and applications, and how they compare to large language models (LLMs).
Dr Ana Rojo-Echeburúa's photo

Dr Ana Rojo-Echeburúa

8 min

tutorial

Pixtral 12B: A Guide With Practical Examples

Learn how to use Mistral’s Pixtral 12B interactively via Le Chat or programmatically through the API available on La Plateforme.
François Aubry's photo

François Aubry

8 min

tutorial

Pixtral Large: A Guide With Examples

Learn how to use Mistral’s Pixtral Large via Le Chat or access it programmatically through the API on La Plateforme.
Aashi Dutt's photo

Aashi Dutt

8 min

tutorial

OpenAI Realtime API: A Guide With Examples

Learn how to build real-time AI applications with OpenAI's Realtime API. This tutorial covers WebSockets, Node.js setup, text/audio messaging, function calling, and deploying a React voice assistant demo.
François Aubry's photo

François Aubry

15 min

tutorial

CrewAI: A Guide With Examples of Multi AI Agent Systems

CrewAI is a platform that enables developers to build and deploy automated workflows using multiple AI agents that collaborate to perform complex tasks.
Bhavishya Pandit's photo

Bhavishya Pandit

9 min

tutorial

Replit Agent: A Guide With Practical Examples

Learn how to set up Replit Agent and discover how to use it through an example walkthrough and 10 real-world use cases.
Dr Ana Rojo-Echeburúa's photo

Dr Ana Rojo-Echeburúa

10 min

See MoreSee More