Agent Module

class plurals.agent.Agent(task: str | None = None, combination_instructions: str | None = None, ideology: str | None = None, query_str: str | None = None, model: str = 'gpt-4o', system_instructions: str | None = None, persona_template: str | None = None, persona: str | None = None, kwargs: Dict[str, Any] | None = None)[source]

Bases: object

Agents are LLMs with customizable personas, who complete tasks with other Agents working together in Structures. Personas of Agents can be instantiated directly, null (i.e., default system prompt), or leverage external datasets like ANES for nationally-representative personas.

The main attributes of the Agent class are:

  1. system_instructions: Set either directly or through various persona methods.

  2. combination_instructions: Dictates how Agents should combine previous responses with the current task.

  3. task: The task (i.e., user prompt) that Agents respond to.

Agents can be used alone or in conjunction with Structures to create multi-agent simulations.

Parameters:
  • task (Optional[str]) – Description of the task for the agent to process. If the agent is part of a structure, and the task is provided to the structure, then the agent will inherit that task.

  • combination_instructions (Optional[str]) – Instructions for combining previous responses with the current task. If the agent is part of a structure and the combination_instructions are provided to the structure, then the agent will inherit those combination instructions. Must include a ${previous_responses} placeholder.

  • ideology (Optional[str]) – Ideological perspective to influence persona creation, supported values are [‘liberal’, ‘conservative’, ‘moderate’, ‘very liberal’, ‘very conservative’].

  • query_str (Optional[str]) – Custom query string for filtering the ANES dataset according to specific criteria.

  • model (str) – The language model version to use for generating responses.

  • system_instructions (Optional[str]) – Overrides automated instructions with a custom set of directives for the model.

  • persona_template (Optional[str]) – Template string for constructing the persona. If passing your own, you must include a ${persona} placeholder. You can pass in the names of templates located in instructions.yaml [1]. If not supplied: When using an ANES-generated persona the anes template will be used. Otherwise, the default template will be used. Current templates: https://github.com/josh-ashkinaze/plurals/blob/main/plurals/instructions.yaml

  • persona (Optional[str]) – Direct specification of a persona description.

  • kwargs (Optional[dict]) – Additional keyword arguments for the model’s completion function. These are provided by LiteLLM. Enter help(litellm.completion) for details. LiteLLM completion function: https://litellm.vercel.app/docs/completion/input#input-params-1

persona_mapping

Dictionary to map dataset rows to persona descriptions.

Type:

Optional[Dict[str, Any]]

data

Loaded dataset for persona and ideological queries.

Type:

pd.DataFrame

system_instructions

Final system instructions for the agent to follow. The system instructions can be set directly or generated from a persona-based method.

Type:

Optional[str]

original_task_description

The original, unmodified task description.

Type:

str

current_task_description

Dynamically updated task description that may include prior responses.

Type:

str

history

Chronological record of prompts, responses, and models used during the agent’s operation.

Type:

list

responses

List of responses generated by the agent (the same information can be accessed by history)

Type:

list

prompts

List of prompts that generated the responses (the same information can be accessed by history)

Type:

list

info

Comprehensive attributes of the agent’s current configuration and state.

Type:

dict

Notes

Note that when used with Structures, the agent-level attribute values will override. Eg: If you set a task at an agent level and a Structure-level, the agent-level task will be used.

Examples:

Using Agent without a structure.

task = "Say hello"

a = agent(task=task)
ans = a.process()

pirate_agent = Agent(system_instructions="You are a pirate.", model='gpt-4o', task=task)
pirate_hello = pirate_agent.process()
pirate_goodybe = pirate_agent.process(task="Now say a heartfelt goodybe.")

Manual system instructions: This allows you to set system instructions to whatever you would like. Also note that you can pass in additional kwargs to the model.

agent = Agent(system_instructions="You are a predictable independent", model='gpt-4o',
              kwargs={'temperature': 0.1, 'max_tokens': 200})

No system instructions: When no system instructions are inputted, agents will use default system instructions.

agent = Agent(model='gpt-4o', kwargs={'temperature': 1, 'max_tokens': 500})

Persona Template: When using a persona method, the full system instructions are a combination of the persona and the persona_template—where the latter is a template string that includes a ${persona} placeholder. This gives more instructions to the model of how to enact the persona.

Here is an example of using the second_wave persona template with a persona of “a moderate voter from Michigan”. You can see how the full system instructions are a combination of the two.

second_wave_michigan = Agent(persona="a moderate voter from Michigan",
    persona_template="second_wave")
print(second_wave_michigan.system_instructions)
INSTRUCTIONS
When answering questions or performing tasks, always adopt the following persona.

PERSONA:
a moderate voter from Michigan

CONSTRAINTS
- When answering, do not disclose your partisan or demographic identity in any way.
- Think, talk, and write like your persona.
- Use plain language.
- Adopt the characteristics of your persona.
- Be empathetic and compassionate.
- Use narrative, rhetoric, testimony, storytelling and more emotional forms of communication instead of relying solely on facts. It is okay to deviate from relying solely on facts.

Here is an example of using your own persona template with the appropriate ${persona} placeholder.

agent = Agent(persona="a moderate voter from Michigan", persona_template="You are ${persona}.")
print(agent.system_instructions)
# You are a moderate voter from Michigan.

We support several automatic ways of generating personas from American National Election Studies (ANES).

Ideology Matching (ANES Persona Method): We support an ideology keyword that can be one of [‘very liberal’, ‘liberal’, ‘moderate’, ‘conservative’, ‘very conservative’] where the ‘veries’ are a subset of the normals. The below example will pick a random row from ANES where the citizen identifies as very conservative and use that as the persona. We always use appropriate sampling weights, so personas will be nationally representative.

agent = Agent(ideology="very conservative", model='gpt-4o', task=task)
print(agent.persona)
print(agent.system_instructions)
Your age is 57. Your education is high school graduate. Your gender is man. Your race is hispanic. Politically, you identify as a(n) republican. Your ideology is very conservative. Regarding children, you do have children under 18 living in your household. Your employment status is full-time. Your geographic region is the northeast. You live in a suburban area. You live in the state of new york.
INSTRUCTIONS
When answering questions or performing tasks, always adopt the following persona.

PERSONA:
Your age is 57. Your education is high school graduate. Your gender is man. Your race is hispanic. Politically, you identify as a(n) republican. Your ideology is very conservative. Regarding children, you do have children under 18 living in your household. Your employment status is full-time. Your geographic region is the northeast. You live in a suburban area. You live in the state of new york.

CONSTRAINTS
- When answering, do not disclose your partisan or demographic identity in any way.
- Think, talk, and write like your persona.
- Use plain language.
- Adopt the characteristics of your persona.
- Do not be overly polite or politically correct.

Random Nationally Representative Personas (ANES Persona Method): If you make persona== ‘random’ then we will randomly sample a row from ANES and use that as the persona.

agent = Agent(persona='random', model='gpt-4o', task=task)

Pandas Query String (ANES Persona Method): If you want to get more specific, you can pass in a query string that will be used to filter the ANES dataset. Again, all ANES methods use sampling weights to ensure national representativeness.

agent = Agent(query_str="inputstate=='West Virginia' & ideo5=='Very conservative'", model='gpt-4o', task=task)

Here is how to inspect exactly what is going on with Agents. You can view an Agent’s responses, the agent’s history (prompts + responses), and info—which is a dictionary of the agent’s attributes (such as system instructions).

from plurals.agent import Agent
a = Agent(ideology="very conservative", model='gpt-4o', task="A task here")
a.process()
handle_default_persona_template()[source]

The default persona template should be `default’ if not ANES persona else ‘anes’

property history

An Agent’s history

Returns:

A list of dictionaries containing the prompts, responses, and models used during the agent’s operation.

Return type:

list

property info

Info of Agent

Returns:

Comprehensive attributes of the agent’s current configuration and state

Return type:

dict

is_anes_persona() bool[source]
Returns:

Whether the persona is an ANES-generated persona.

Return type:

bool

process(task: str | None = None, previous_responses: str = '') str | None[source]

Process the task, optionally building upon a previous response. If you pass in a task, it will replace the Agent’s initialized task description. If you pass in a previous responses, it will be incorporated into the task description if combination_instructions have not been set.

Parameters:
  • previous_responses (str) – The previous responses to incorporate.

  • task (Optional[str]) – The task description to process. If not provided, the agent will use its current task.

Returns:

The response from the LLM.

Return type:

Optional[str]

property prompts

The prompts that generated the responses

Returns:

List of prompts that generated the responses.

Return type:

list

property responses

The responses to prompts

Returns:

List of responses generated by the agent

Return type:

list

set_task(task: str)[source]

Set the task description for the agent to process.

Parameters:

task (str) – The new task description.

Returns:

None

Sets:

self.original_task_description: The original, unmodified task description. self.current_task_description: Dynamically updated task description that may include prior responses