Importing agents

This notebook provides sample EDSL code for simulating surveys with agent personas imported from Persona Hub, an open-source repository provided by Hugging Face.

EDSL is an open-source library for simulating surveys, experiments and other research with AI agents and large language models. Before running the code below, please ensure that you have installed the EDSL library and either activated remote inference from your Coop account or stored API keys for the language models that you want to use with EDSL. Please also see our documentation page for tips and tutorials on getting started using EDSL.

Importing the data

Persona Hub: https://github.com/tencent-ailab/persona-hub

[1]:
# pip install datasets
[2]:
from datasets import load_dataset

ds = load_dataset("proj-persona/PersonaHub", "instruction")

Selecting data

Here we select some personas to use.

[3]:
num_agents = 10

personas_list = ds['train']['input persona'][:num_agents]
personas_list
[3]:
['A theater manager or events coordinator interested in understanding the operational aspects, facilities, and programming of performing arts centers, such as the Broward Center.',
 'An urban planner looking to understand the distribution and organization of public services in the Halifax Regional Municipality.',
 "A high school literature teacher looking for supplementary materials to enrich their curriculum and provide students with a deeper understanding of their state's cultural heritage.",
 'A science fiction writer, exploring the use of secret trials as a theme in stories that examine surveillance, privacy, and power dynamics in society.',
 'A financial analyst specializing in Asian markets and wealthy individuals, interested in tracking the investments and philanthropic activities of billionaires like Gerald Chan.',
 'A high school physics teacher who enjoys applying physics concepts to various sports, curious about the effects of water resistance and body positioning in Paralympic swimming.',
 'A high school physical education teacher seeking to incorporate Paralympic history and achievements into the curriculum to inspire and educate students about inclusivity in sports.',
 'A high school history teacher creating lesson plans on South American civilizations and their regional diversity.',
 'A cultural anthropologist studying the representation and adaptation of traditional folklore in contemporary media, particularly in television and film.',
 'A high school earth science teacher looking for real-world examples to explain climate zones, soil types, and human-environment interactions.']

Creating agents

We create an agent in EDSL by passing a dictionary of traits (such as a persona) to an Agent object. Here we use a method for generating a set of agents from a list of traits at once (a list of the personas). Learn more about designing agents in EDSL.

[4]:
from edsl import AgentList

agents = AgentList.from_list("persona", personas_list)

Using agents to answer a survey

Here we construct some questions and administer them to the agents. EDSL comes with many common question types that we can choose from based on the form of the response that we want to get back from a model. Learn more about constructing surveys with different question types, logic and rules.

[5]:
from edsl import QuestionMultipleChoice, QuestionLinearScale, Survey

q1 = QuestionMultipleChoice(
    question_name = "preferred_mode_commute",
    question_text = "What is your preferred mode of commuting to work?",
    question_options = [ "Car", "Public transportation", "Bike", "Walk", "Work from home", "Other" ]
)

q2 = QuestionLinearScale(
    question_name = "work_from_home",
    question_text = "On a scale from 1 to 5, how easy is it for you to work from home?",
    question_options = [1,2,3,4,5],
    option_labels = {1:"Not at all easy", 5:"Very easy"}
)

survey = Survey([q1, q2])

Selecting language models

EDSL works with many popular language models that we can select to generate the responses for the agents.

To see a list of all services:

[6]:
from edsl import Model

Model.services()
[6]:
  Service Name
0 anthropic
1 azure
2 bedrock
3 deep_infra
4 deepseek
5 google
6 groq
7 mistral
8 ollama
9 openai
10 perplexity
11 together
12 xai

To see a list of all available models:

[7]:
# Model.available()

To select models to use with a survey:

[8]:
from edsl import ModelList, Model

models = ModelList(
    Model(m) for m in ["gemini-1.5-flash", "gpt-4o"]
)

We run a survey by adding the agents and models, and then calling the run() method. This generates a formatted dataset of Results:

[9]:
results = survey.by(agents).by(models).run()
Job Status (2025-03-03 10:41:36)
Job UUID 9478009b-a7b3-4718-a878-13e283629e1d
Progress Bar URL https://www.expectedparrot.com/home/remote-job-progress/9478009b-a7b3-4718-a878-13e283629e1d
Exceptions Report URL None
Results UUID c8823538-48ac-44d0-a025-9833e66be403
Results URL https://www.expectedparrot.com/content/c8823538-48ac-44d0-a025-9833e66be403
Current Status: Job completed and Results stored on Coop: https://www.expectedparrot.com/content/c8823538-48ac-44d0-a025-9833e66be403

Analyzing results

EDSL comes with built-in methods for analysis. Here we inspect the responses in a table:

[10]:
results.select("model", "persona", "preferred_mode_commute", "work_from_home")
[10]:
  model.model agent.persona answer.preferred_mode_commute answer.work_from_home
0 gemini-1.5-flash A theater manager or events coordinator interested in understanding the operational aspects, facilities, and programming of performing arts centers, such as the Broward Center. Car 1
1 gpt-4o A theater manager or events coordinator interested in understanding the operational aspects, facilities, and programming of performing arts centers, such as the Broward Center. Car 2
2 gemini-1.5-flash An urban planner looking to understand the distribution and organization of public services in the Halifax Regional Municipality. Public transportation 3
3 gpt-4o An urban planner looking to understand the distribution and organization of public services in the Halifax Regional Municipality. Public transportation 4
4 gemini-1.5-flash A high school literature teacher looking for supplementary materials to enrich their curriculum and provide students with a deeper understanding of their state's cultural heritage. Car 3
5 gpt-4o A high school literature teacher looking for supplementary materials to enrich their curriculum and provide students with a deeper understanding of their state's cultural heritage. Car 3
6 gemini-1.5-flash A science fiction writer, exploring the use of secret trials as a theme in stories that examine surveillance, privacy, and power dynamics in society. Work from home 5
7 gpt-4o A science fiction writer, exploring the use of secret trials as a theme in stories that examine surveillance, privacy, and power dynamics in society. Work from home 5
8 gemini-1.5-flash A financial analyst specializing in Asian markets and wealthy individuals, interested in tracking the investments and philanthropic activities of billionaires like Gerald Chan. Work from home 4
9 gpt-4o A financial analyst specializing in Asian markets and wealthy individuals, interested in tracking the investments and philanthropic activities of billionaires like Gerald Chan. Work from home 5
10 gemini-1.5-flash A high school physics teacher who enjoys applying physics concepts to various sports, curious about the effects of water resistance and body positioning in Paralympic swimming. Car 3
11 gpt-4o A high school physics teacher who enjoys applying physics concepts to various sports, curious about the effects of water resistance and body positioning in Paralympic swimming. Bike 2
12 gemini-1.5-flash A high school physical education teacher seeking to incorporate Paralympic history and achievements into the curriculum to inspire and educate students about inclusivity in sports. Car 1
13 gpt-4o A high school physical education teacher seeking to incorporate Paralympic history and achievements into the curriculum to inspire and educate students about inclusivity in sports. Bike 1
14 gemini-1.5-flash A high school history teacher creating lesson plans on South American civilizations and their regional diversity. Car 3
15 gpt-4o A high school history teacher creating lesson plans on South American civilizations and their regional diversity. Car 4
16 gemini-1.5-flash A cultural anthropologist studying the representation and adaptation of traditional folklore in contemporary media, particularly in television and film. Work from home 4
17 gpt-4o A cultural anthropologist studying the representation and adaptation of traditional folklore in contemporary media, particularly in television and film. Work from home 4
18 gemini-1.5-flash A high school earth science teacher looking for real-world examples to explain climate zones, soil types, and human-environment interactions. Car 2
19 gpt-4o A high school earth science teacher looking for real-world examples to explain climate zones, soil types, and human-environment interactions. Car 3

Constructing traits

In comparing model responses it can be convenient to include shortnames for traits in addition to narrative personas–e.g., just the name of the agent’s occupation, age, etc. Here we run a question to extract the occupation from each persona in order to store it as a separate trait of each agent. We use Scenario objects to represent the data (personas) that we add to the question when we run it. Learn more about using scenarios to parameterize questions with data and context.

[11]:
from edsl import QuestionExtract

q = QuestionExtract(
    question_name = "occupation",
    question_text = "{{ scenario.persona }}",
    answer_template = {"occupation":"artist"}
)

Creating scenarios for the personas in order to add them to the question:

[12]:
from edsl import ScenarioList

scenarios = ScenarioList.from_list("persona", personas_list)
[13]:
results = q.by(scenarios).run()
Job Status (2025-03-03 10:41:46)
Job UUID c56acffd-137d-4800-9b1f-ad42e4f1a603
Progress Bar URL https://www.expectedparrot.com/home/remote-job-progress/c56acffd-137d-4800-9b1f-ad42e4f1a603
Exceptions Report URL None
Results UUID 9f136a82-8ae5-4648-a14e-eab2d5ab1ebc
Results URL https://www.expectedparrot.com/content/9f136a82-8ae5-4648-a14e-eab2d5ab1ebc
Current Status: Job completed and Results stored on Coop: https://www.expectedparrot.com/content/9f136a82-8ae5-4648-a14e-eab2d5ab1ebc
[14]:
results.select("persona", "occupation")
[14]:
  scenario.persona answer.occupation
0 A theater manager or events coordinator interested in understanding the operational aspects, facilities, and programming of performing arts centers, such as the Broward Center. {'occupation': 'theater manager or events coordinator'}
1 An urban planner looking to understand the distribution and organization of public services in the Halifax Regional Municipality. {'occupation': 'urban planner'}
2 A high school literature teacher looking for supplementary materials to enrich their curriculum and provide students with a deeper understanding of their state's cultural heritage. {'occupation': 'high school literature teacher'}
3 A science fiction writer, exploring the use of secret trials as a theme in stories that examine surveillance, privacy, and power dynamics in society. {'occupation': 'science fiction writer'}
4 A financial analyst specializing in Asian markets and wealthy individuals, interested in tracking the investments and philanthropic activities of billionaires like Gerald Chan. {'occupation': 'financial analyst'}
5 A high school physics teacher who enjoys applying physics concepts to various sports, curious about the effects of water resistance and body positioning in Paralympic swimming. {'occupation': 'high school physics teacher'}
6 A high school physical education teacher seeking to incorporate Paralympic history and achievements into the curriculum to inspire and educate students about inclusivity in sports. {'occupation': 'high school physical education teacher'}
7 A high school history teacher creating lesson plans on South American civilizations and their regional diversity. {'occupation': 'high school history teacher'}
8 A cultural anthropologist studying the representation and adaptation of traditional folklore in contemporary media, particularly in television and film. {'occupation': 'cultural anthropologist'}
9 A high school earth science teacher looking for real-world examples to explain climate zones, soil types, and human-environment interactions. {'occupation': 'high school earth science teacher'}

Designing agents

Here we recreate agents with both the personas and occupations as traits:

[15]:
occupations_list = [o['occupation'] for o in results.select("occupation").to_list()]
occupations_list
[15]:
['theater manager or events coordinator',
 'urban planner',
 'high school literature teacher',
 'science fiction writer',
 'financial analyst',
 'high school physics teacher',
 'high school physical education teacher',
 'high school history teacher',
 'cultural anthropologist',
 'high school earth science teacher']
[16]:
t = list(zip(personas_list, occupations_list))
[17]:
from edsl import AgentList, Agent

agents = AgentList(
    Agent(traits = {"persona":p, "occupation":o}) for p,o in t
)

Running a survey

Here we rerun the survey and then filter and sort results by agent traits:

[18]:
results = survey.by(agents).by(models).run()
Job Status (2025-03-03 10:42:08)
Job UUID c5e74cf4-e020-4a5d-9ad7-abbc3aee5f12
Progress Bar URL https://www.expectedparrot.com/home/remote-job-progress/c5e74cf4-e020-4a5d-9ad7-abbc3aee5f12
Exceptions Report URL None
Results UUID c6c0bbf1-804a-4057-b60c-7284fab3b105
Results URL https://www.expectedparrot.com/content/c6c0bbf1-804a-4057-b60c-7284fab3b105
Current Status: Job completed and Results stored on Coop: https://www.expectedparrot.com/content/c6c0bbf1-804a-4057-b60c-7284fab3b105
[19]:
(
    results
    .filter("model.model == 'gpt-4o'")
    .sort_by("work_from_home", reverse=True)
    .select("model", "occupation", "preferred_mode_commute", "work_from_home")
)
[19]:
  model.model agent.occupation answer.preferred_mode_commute answer.work_from_home
0 gpt-4o science fiction writer Work from home 5
1 gpt-4o financial analyst Work from home 5
2 gpt-4o cultural anthropologist Work from home 5
3 gpt-4o urban planner Public transportation 4
4 gpt-4o high school literature teacher Car 3
5 gpt-4o high school physics teacher Bike 3
6 gpt-4o high school history teacher Car 3
7 gpt-4o high school earth science teacher Car 3
8 gpt-4o theater manager or events coordinator Car 2
9 gpt-4o high school physical education teacher Bike 1

Posting to the Coop

The Coop is a platform for creating, storing and sharing LLM-based research. It is fully integrated with EDSL and accessible from your workspace or Coop account page. Learn more about creating an account and using the Coop.

Here we demonstrate how to post this notebook:

[20]:
from edsl import Notebook

nb = Notebook(path = "import_agents.ipynb")

if refresh := False:
    nb.push(
        description = "Importing agents",
        alias = "importing-agents-notebook",
        visibility = "public"
    )
else:
    nb.patch('e0f3c111-328e-417b-b2ad-aec527adad49', value = nb)