Files
langchain/docs/use_cases/agent_simulations/characters.ipynb
T
f329196cf4 Agents 4 18 (#3122)
Creating an experimental agents folder, containing BabyAGI, AutoGPT, and
later, other examples

---------

Co-authored-by: Rahul Behal <rahulbehal01@hotmail.com>
Co-authored-by: Harrison Chase <hw.chase.17@gmail.com>
2023-04-18 21:41:03 -07:00

54 KiB

Generative Agents in LangChain

This notebook implements a generative agent based on the paper Generative Agents: Interactive Simulacra of Human Behavior by Park, et. al.

In it, we leverage a time-weighted Memory object backed by a LangChain Retriever.

In [1]:
# Use termcolor to make it easy to colorize the outputs.
!pip install termcolor > /dev/null
In [2]:
import re
from datetime import datetime, timedelta
from typing import List, Optional, Tuple
from termcolor import colored

from pydantic import BaseModel, Field

from langchain import LLMChain
from langchain.chat_models import ChatOpenAI
from langchain.docstore import InMemoryDocstore
from langchain.embeddings import OpenAIEmbeddings
from langchain.prompts import PromptTemplate
from langchain.retrievers import TimeWeightedVectorStoreRetriever
from langchain.schema import BaseLanguageModel, Document
from langchain.vectorstores import FAISS
In [3]:
USER_NAME = "Person A" # The name you want to use when interviewing the agent.
LLM = ChatOpenAI(max_tokens=1500) # Can be any LLM you want.

Generative Agent Memory Components

This tutorial highlights the memory of generative agents and its impact on their behavior. The memory varies from standard LangChain Chat memory in two aspects:

  1. Memory Formation

    Generative Agents have extended memories, stored in a single stream:

    1. Observations - from dialogues or interactions with the virtual world, about self or others
    2. Reflections - resurfaced and summarized core memories
  2. Memory Recall

    Memories are retrieved using a weighted sum of salience, recency, and importance.

Review the definition below, focusing on add_memory and summarize_related_memories methods.

In [4]:
class GenerativeAgent(BaseModel):
    """A character with memory and innate characteristics."""
    
    name: str
    age: int
    traits: str
    """The traits of the character you wish not to change."""
    status: str
    """Current activities of the character."""
    llm: BaseLanguageModel
    memory_retriever: TimeWeightedVectorStoreRetriever
    """The retriever to fetch related memories."""
    verbose: bool = False
    
    reflection_threshold: Optional[float] = None
    """When the total 'importance' of memories exceeds the above threshold, stop to reflect."""
    
    current_plan: List[str] = []
    """The current plan of the agent."""
    
    summary: str = ""  #: :meta private:
    summary_refresh_seconds: int= 3600  #: :meta private:
    last_refreshed: datetime =Field(default_factory=datetime.now)  #: :meta private:
    daily_summaries: List[str] #: :meta private:
    memory_importance: float = 0.0 #: :meta private:
    max_tokens_limit: int = 1200 #: :meta private:
    
    class Config:
        """Configuration for this pydantic object."""

        arbitrary_types_allowed = True

    @staticmethod
    def _parse_list(text: str) -> List[str]:
        """Parse a newline-separated string into a list of strings."""
        lines = re.split(r'\n', text.strip())
        return [re.sub(r'^\s*\d+\.\s*', '', line).strip() for line in lines]


    def _compute_agent_summary(self):
        """"""
        prompt = PromptTemplate.from_template(
            "How would you summarize {name}'s core characteristics given the"
            +" following statements:\n"
            +"{related_memories}"
            + "Do not embellish."
            +"\n\nSummary: "
        )
        # The agent seeks to think about their core characteristics.
        relevant_memories = self.fetch_memories(f"{self.name}'s core characteristics")
        relevant_memories_str = "\n".join([f"{mem.page_content}" for mem in relevant_memories])
        chain = LLMChain(llm=self.llm, prompt=prompt, verbose=self.verbose)
        return chain.run(name=self.name, related_memories=relevant_memories_str).strip()
    
    def _get_topics_of_reflection(self, last_k: int = 50) -> Tuple[str, str, str]:
        """Return the 3 most salient high-level questions about recent observations."""
        prompt = PromptTemplate.from_template(
            "{observations}\n\n"
            + "Given only the information above, what are the 3 most salient"
            + " high-level questions we can answer about the subjects in the statements?"
            + " Provide each question on a new line.\n\n"
        )
        reflection_chain = LLMChain(llm=self.llm, prompt=prompt, verbose=self.verbose)
        observations = self.memory_retriever.memory_stream[-last_k:]
        observation_str = "\n".join([o.page_content for o in observations])
        result = reflection_chain.run(observations=observation_str)
        return self._parse_list(result)
    
    def _get_insights_on_topic(self, topic: str) -> List[str]:
        """Generate 'insights' on a topic of reflection, based on pertinent memories."""
        prompt = PromptTemplate.from_template(
            "Statements about {topic}\n"
            +"{related_statements}\n\n"
            + "What 5 high-level insights can you infer from the above statements?"
            + " (example format: insight (because of 1, 5, 3))"
        )
        related_memories = self.fetch_memories(topic)
        related_statements = "\n".join([f"{i+1}. {memory.page_content}" 
                                        for i, memory in 
                                        enumerate(related_memories)])
        reflection_chain = LLMChain(llm=self.llm, prompt=prompt, verbose=self.verbose)
        result = reflection_chain.run(topic=topic, related_statements=related_statements)
        # TODO: Parse the connections between memories and insights
        return self._parse_list(result)
    
    def pause_to_reflect(self) -> List[str]:
        """Reflect on recent observations and generate 'insights'."""
        print(colored(f"Character {self.name} is reflecting", "blue"))
        new_insights = []
        topics = self._get_topics_of_reflection()
        for topic in topics:
            insights = self._get_insights_on_topic( topic)
            for insight in insights:
                self.add_memory(insight)
            new_insights.extend(insights)
        return new_insights
    
    def _score_memory_importance(self, memory_content: str, weight: float = 0.15) -> float:
        """Score the absolute importance of the given memory."""
        # A weight of 0.25 makes this less important than it
        # would be otherwise, relative to salience and time
        prompt = PromptTemplate.from_template(
         "On the scale of 1 to 10, where 1 is purely mundane"
         +" (e.g., brushing teeth, making bed) and 10 is"
         + " extremely poignant (e.g., a break up, college"
         + " acceptance), rate the likely poignancy of the"
         + " following piece of memory. Respond with a single integer."
         + "\nMemory: {memory_content}"
         + "\nRating: "
        )
        chain = LLMChain(llm=self.llm, prompt=prompt, verbose=self.verbose)
        score = chain.run(memory_content=memory_content).strip()
        match = re.search(r"^\D*(\d+)", score)
        if match:
            return (float(score[0]) / 10) * weight
        else:
            return 0.0


    def add_memory(self, memory_content: str) -> List[str]:
        """Add an observation or memory to the agent's memory."""
        importance_score = self._score_memory_importance(memory_content)
        self.memory_importance += importance_score
        document = Document(page_content=memory_content, metadata={"importance": importance_score})
        result = self.memory_retriever.add_documents([document])

        # After an agent has processed a certain amount of memories (as measured by
        # aggregate importance), it is time to reflect on recent events to add
        # more synthesized memories to the agent's memory stream.
        if (self.reflection_threshold is not None 
            and self.memory_importance > self.reflection_threshold
            and self.status != "Reflecting"):
            old_status = self.status
            self.status = "Reflecting"
            self.pause_to_reflect()
            # Hack to clear the importance from reflection
            self.memory_importance = 0.0
            self.status = old_status
        return result
    
    def fetch_memories(self, observation: str) -> List[Document]:
        """Fetch related memories."""
        return self.memory_retriever.get_relevant_documents(observation)
    
        
    def get_summary(self, force_refresh: bool = False) -> str:
        """Return a descriptive summary of the agent."""
        current_time = datetime.now()
        since_refresh = (current_time - self.last_refreshed).seconds
        if not self.summary or since_refresh >= self.summary_refresh_seconds or force_refresh:
            self.summary = self._compute_agent_summary()
            self.last_refreshed = current_time
        return (
            f"Name: {self.name} (age: {self.age})"
            +f"\nInnate traits: {self.traits}"
            +f"\n{self.summary}"
        )
    
    def get_full_header(self, force_refresh: bool = False) -> str:
        """Return a full header of the agent's status, summary, and current time."""
        summary = self.get_summary(force_refresh=force_refresh)
        current_time_str =  datetime.now().strftime("%B %d, %Y, %I:%M %p")
        return f"{summary}\nIt is {current_time_str}.\n{self.name}'s status: {self.status}"

    
    
    def _get_entity_from_observation(self, observation: str) -> str:
        prompt = PromptTemplate.from_template(
            "What is the observed entity in the following observation? {observation}"
            +"\nEntity="
        )
        chain = LLMChain(llm=self.llm, prompt=prompt, verbose=self.verbose)
        return chain.run(observation=observation).strip()

    def _get_entity_action(self, observation: str, entity_name: str) -> str:
        prompt = PromptTemplate.from_template(
            "What is the {entity} doing in the following observation? {observation}"
            +"\nThe {entity} is"
        )
        chain = LLMChain(llm=self.llm, prompt=prompt, verbose=self.verbose)
        return chain.run(entity=entity_name, observation=observation).strip()
    
    def _format_memories_to_summarize(self, relevant_memories: List[Document]) -> str:
        content_strs = set()
        content = []
        for mem in relevant_memories:
            if mem.page_content in content_strs:
                continue
            content_strs.add(mem.page_content)
            created_time = mem.metadata["created_at"].strftime("%B %d, %Y, %I:%M %p")
            content.append(f"- {created_time}: {mem.page_content.strip()}")
        return "\n".join([f"{mem}" for mem in content])
    
    def summarize_related_memories(self, observation: str) -> str:
        """Summarize memories that are most relevant to an observation."""
        entity_name = self._get_entity_from_observation(observation)
        entity_action = self._get_entity_action(observation, entity_name)
        q1 = f"What is the relationship between {self.name} and {entity_name}"
        relevant_memories = self.fetch_memories(q1) # Fetch memories related to the agent's relationship with the entity
        q2 = f"{entity_name} is {entity_action}"
        relevant_memories += self.fetch_memories(q2) # Fetch things related to the entity-action pair
        context_str = self._format_memories_to_summarize(relevant_memories)
        prompt = PromptTemplate.from_template(
            "{q1}?\nContext from memory:\n{context_str}\nRelevant context: "
        )
        chain = LLMChain(llm=self.llm, prompt=prompt, verbose=self.verbose)
        return chain.run(q1=q1, context_str=context_str.strip()).strip()
    
    def _get_memories_until_limit(self, consumed_tokens: int) -> str:
        """Reduce the number of tokens in the documents."""
        result = []
        for doc in self.memory_retriever.memory_stream[::-1]:
            if consumed_tokens >= self.max_tokens_limit:
                break
            consumed_tokens += self.llm.get_num_tokens(doc.page_content)
            if consumed_tokens < self.max_tokens_limit:
                result.append(doc.page_content) 
        return "; ".join(result[::-1])
    
    def _generate_reaction(
        self,
        observation: str,
        suffix: str
    ) -> str:
        """React to a given observation."""
        prompt = PromptTemplate.from_template(
                "{agent_summary_description}"
                +"\nIt is {current_time}."
                +"\n{agent_name}'s status: {agent_status}"
                + "\nSummary of relevant context from {agent_name}'s memory:"
                +"\n{relevant_memories}"
                +"\nMost recent observations: {recent_observations}"
                + "\nObservation: {observation}"
                + "\n\n" + suffix
        )
        agent_summary_description = self.get_summary()
        relevant_memories_str = self.summarize_related_memories(observation)
        current_time_str = datetime.now().strftime("%B %d, %Y, %I:%M %p")
        kwargs = dict(agent_summary_description=agent_summary_description,
                      current_time=current_time_str,
                      relevant_memories=relevant_memories_str,
                      agent_name=self.name,
                      observation=observation,
                     agent_status=self.status)
        consumed_tokens = self.llm.get_num_tokens(prompt.format(recent_observations="", **kwargs))
        kwargs["recent_observations"] = self._get_memories_until_limit(consumed_tokens)
        action_prediction_chain = LLMChain(llm=self.llm, prompt=prompt)
        result = action_prediction_chain.run(**kwargs)
        return result.strip()
    
    def generate_reaction(self, observation: str) -> Tuple[bool, str]:
        """React to a given observation."""
        call_to_action_template = (
            "Should {agent_name} react to the observation, and if so,"
            +" what would be an appropriate reaction? Respond in one line."
            +' If the action is to engage in dialogue, write:\nSAY: "what to say"'
            +"\notherwise, write:\nREACT: {agent_name}'s reaction (if anything)."
            + "\nEither do nothing, react, or say something but not both.\n\n"
        )
        full_result = self._generate_reaction(observation, call_to_action_template)
        result = full_result.strip().split('\n')[0]
        self.add_memory(f"{self.name} observed {observation} and reacted by {result}")
        if "REACT:" in result:
            reaction = result.split("REACT:")[-1].strip()
            return False, f"{self.name} {reaction}"
        if "SAY:" in result:
            said_value = result.split("SAY:")[-1].strip()
            return True, f"{self.name} said {said_value}"
        else:
            return False, result

    def generate_dialogue_response(self, observation: str) -> Tuple[bool, str]:
        """React to a given observation."""
        call_to_action_template = (
            'What would {agent_name} say? To end the conversation, write: GOODBYE: "what to say". Otherwise to continue the conversation, write: SAY: "what to say next"\n\n'
        )
        full_result = self._generate_reaction(observation, call_to_action_template)
        result = full_result.strip().split('\n')[0]
        if "GOODBYE:" in result:
            farewell = result.split("GOODBYE:")[-1].strip()
            self.add_memory(f"{self.name} observed {observation} and said {farewell}")
            return False, f"{self.name} said {farewell}"
        if "SAY:" in result:
            response_text = result.split("SAY:")[-1].strip()
            self.add_memory(f"{self.name} observed {observation} and said {response_text}")
            return True, f"{self.name} said {response_text}"
        else:
            return False, result

Memory Lifecycle

Summarizing the above key methods: add_memory and summarize_related_memories.

When an agent makes an observation, it stores the memory:

  1. Language model scores the memory's importance (1 for mundane, 10 for poignant)
  2. Observation and importance are stored within a document by TimeWeightedVectorStoreRetriever, with a last_accessed_time.

When an agent responds to an observation:

  1. Generates query(s) for retriever, which fetches documents based on salience, recency, and importance.
  2. Summarizes the retrieved information
  3. Updates the last_accessed_time for the used documents.

Create a Generative Character

Now that we've walked through the definition, we will create two characters named "Tommie" and "Eve".

In [5]:
import math
import faiss

def relevance_score_fn(score: float) -> float:
    """Return a similarity score on a scale [0, 1]."""
    # This will differ depending on a few things:
    # - the distance / similarity metric used by the VectorStore
    # - the scale of your embeddings (OpenAI's are unit norm. Many others are not!)
    # This function converts the euclidean norm of normalized embeddings
    # (0 is most similar, sqrt(2) most dissimilar)
    # to a similarity function (0 to 1)
    return 1.0 - score / math.sqrt(2)

def create_new_memory_retriever():
    """Create a new vector store retriever unique to the agent."""
    # Define your embedding model
    embeddings_model = OpenAIEmbeddings()
    # Initialize the vectorstore as empty
    embedding_size = 1536
    index = faiss.IndexFlatL2(embedding_size)
    vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {}, relevance_score_fn=relevance_score_fn)
    return TimeWeightedVectorStoreRetriever(vectorstore=vectorstore, other_score_keys=["importance"], k=15)    
In [6]:
tommie = GenerativeAgent(name="Tommie", 
              age=25,
              traits="anxious, likes design", # You can add more persistent traits here 
              status="looking for a job", # When connected to a virtual world, we can have the characters update their status
              memory_retriever=create_new_memory_retriever(),
              llm=LLM,
              daily_summaries = [
                   "Drove across state to move to a new town but doesn't have a job yet."
               ],
               reflection_threshold = 8, # we will give this a relatively low number to show how reflection works
             )
In [7]:
# The current "Summary" of a character can't be made because the agent hasn't made
# any observations yet.
print(tommie.get_summary())
Name: Tommie (age: 25)
Innate traits: anxious, likes design
Unfortunately, there are no statements provided to summarize Tommie's core characteristics.
In [8]:
# We can give the character memories directly
tommie_memories = [
    "Tommie remembers his dog, Bruno, from when he was a kid",
    "Tommie feels tired from driving so far",
    "Tommie sees the new home",
    "The new neighbors have a cat",
    "The road is noisy at night",
    "Tommie is hungry",
    "Tommie tries to get some rest.",
]
for memory in tommie_memories:
    tommie.add_memory(memory)
In [9]:
# Now that Tommie has 'memories', their self-summary is more descriptive, though still rudimentary.
# We will see how this summary updates after more observations to create a more rich description.
print(tommie.get_summary(force_refresh=True))
Name: Tommie (age: 25)
Innate traits: anxious, likes design
Tommie is observant, nostalgic, tired, and hungry.

Pre-Interview with Character

Before sending our character on their way, let's ask them a few questions.

In [10]:
def interview_agent(agent: GenerativeAgent, message: str) -> str:
    """Help the notebook user interact with the agent."""
    new_message = f"{USER_NAME} says {message}"
    return agent.generate_dialogue_response(new_message)[1]
In [11]:
interview_agent(tommie, "What do you like to do?")
Out [11]:
'Tommie said "I really enjoy design, especially interior design. I find it calming and rewarding to create a space that is both functional and aesthetically pleasing. Unfortunately, I haven\'t been able to find a job in that field yet."'
In [12]:
interview_agent(tommie, "What are you looking forward to doing today?")
Out [12]:
'Tommie said "Well, I\'m actually on the hunt for a job right now. I\'m hoping to find something in the design field, but I\'m open to exploring other options as well. How about you, what are your plans for the day?"'
In [13]:
interview_agent(tommie, "What are you most worried about today?")
Out [13]:
'Tommie said "Honestly, I\'m feeling pretty anxious about finding a job. It\'s been a bit of a struggle and I\'m not sure what my next step should be. But I\'m trying to stay positive and keep pushing forward."'

Step through the day's observations.

In [14]:
# Let's have Tommie start going through a day in the life.
observations = [
    "Tommie wakes up to the sound of a noisy construction site outside his window.",
    "Tommie gets out of bed and heads to the kitchen to make himself some coffee.",
    "Tommie realizes he forgot to buy coffee filters and starts rummaging through his moving boxes to find some.",
    "Tommie finally finds the filters and makes himself a cup of coffee.",
    "The coffee tastes bitter, and Tommie regrets not buying a better brand.",
    "Tommie checks his email and sees that he has no job offers yet.",
    "Tommie spends some time updating his resume and cover letter.",
    "Tommie heads out to explore the city and look for job openings.",
    "Tommie sees a sign for a job fair and decides to attend.",
    "The line to get in is long, and Tommie has to wait for an hour.",
    "Tommie meets several potential employers at the job fair but doesn't receive any offers.",
    "Tommie leaves the job fair feeling disappointed.",
    "Tommie stops by a local diner to grab some lunch.",
    "The service is slow, and Tommie has to wait for 30 minutes to get his food.",
    "Tommie overhears a conversation at the next table about a job opening.",
    "Tommie asks the diners about the job opening and gets some information about the company.",
    "Tommie decides to apply for the job and sends his resume and cover letter.",
    "Tommie continues his search for job openings and drops off his resume at several local businesses.",
    "Tommie takes a break from his job search to go for a walk in a nearby park.",
    "A dog approaches and licks Tommie's feet, and he pets it for a few minutes.",
    "Tommie sees a group of people playing frisbee and decides to join in.",
    "Tommie has fun playing frisbee but gets hit in the face with the frisbee and hurts his nose.",
    "Tommie goes back to his apartment to rest for a bit.",
    "A raccoon tore open the trash bag outside his apartment, and the garbage is all over the floor.",
    "Tommie starts to feel frustrated with his job search.",
    "Tommie calls his best friend to vent about his struggles.",
    "Tommie's friend offers some words of encouragement and tells him to keep trying.",
    "Tommie feels slightly better after talking to his friend.",
]
In [15]:
# Let's send Tommie on their way. We'll check in on their summary every few observations to watch it evolve
for i, observation in enumerate(observations):
    _, reaction = tommie.generate_reaction(observation)
    print(colored(observation, "green"), reaction)
    if ((i+1) % 20) == 0:
        print('*'*40)
        print(colored(f"After {i+1} observations, Tommie's summary is:\n{tommie.get_summary(force_refresh=True)}", "blue"))
        print('*'*40)
Tommie wakes up to the sound of a noisy construction site outside his window. Tommie Tommie groans and covers their head with a pillow, trying to block out the noise.
Tommie gets out of bed and heads to the kitchen to make himself some coffee. Tommie Tommie starts making coffee, feeling grateful for the little bit of energy it will give him.
Tommie realizes he forgot to buy coffee filters and starts rummaging through his moving boxes to find some. Tommie Tommie sighs in frustration and continues to search for the coffee filters.
Tommie finally finds the filters and makes himself a cup of coffee. Tommie Tommie takes a sip of the coffee and feels a little more awake.
The coffee tastes bitter, and Tommie regrets not buying a better brand. Tommie Tommie grimaces at the taste of the coffee and decides to make a mental note to buy a better brand next time.
Tommie checks his email and sees that he has no job offers yet. Tommie Tommie feels disappointed and discouraged, but tries to stay positive and continue the job search.
Tommie spends some time updating his resume and cover letter. Tommie Tommie feels determined to keep working on his job search.
Tommie heads out to explore the city and look for job openings. Tommie Tommie feels hopeful but also anxious as he heads out to explore the city and look for job openings.
Tommie sees a sign for a job fair and decides to attend. Tommie said "That job fair could be a great opportunity to meet potential employers."
The line to get in is long, and Tommie has to wait for an hour. Tommie Tommie feels frustrated and restless while waiting in line.
Tommie meets several potential employers at the job fair but doesn't receive any offers. Tommie Tommie feels disappointed but remains determined to keep searching for job openings.
Tommie leaves the job fair feeling disappointed. Tommie Tommie feels discouraged but remains determined to keep searching for job openings.
Tommie stops by a local diner to grab some lunch. Tommie Tommie feels relieved to take a break from job searching and enjoy a meal.
The service is slow, and Tommie has to wait for 30 minutes to get his food. Tommie Tommie feels impatient and frustrated while waiting for his food.
Tommie overhears a conversation at the next table about a job opening. Tommie said "Excuse me, I couldn't help but overhear about the job opening. Could you tell me more about it?"
Tommie asks the diners about the job opening and gets some information about the company. Tommie said "Could you tell me more about it?"
Tommie decides to apply for the job and sends his resume and cover letter. Tommie said "Thank you for the information, I'll definitely apply for the job and keep my fingers crossed."
Tommie continues his search for job openings and drops off his resume at several local businesses. Tommie Tommie feels hopeful but also anxious as he continues his search for job openings and drops off his resume at several local businesses.
Tommie takes a break from his job search to go for a walk in a nearby park. Tommie Tommie takes a deep breath and enjoys the fresh air in the park.
A dog approaches and licks Tommie's feet, and he pets it for a few minutes. Tommie Tommie smiles and enjoys the momentary distraction from his job search.
****************************************
After 20 observations, Tommie's summary is:
Name: Tommie (age: 25)
Innate traits: anxious, likes design
Tommie is a determined individual who is actively searching for job opportunities. He feels both hopeful and anxious about his search and remains positive despite facing disappointments. He takes breaks to rest and enjoy the little things in life, like going for a walk or grabbing a meal. Tommie is also open to asking for help and seeking information about potential job openings. He is grateful for the little things that give him energy and tries to stay positive even when faced with discouragement. Overall, Tommie's core characteristics include determination, positivity, and a willingness to seek help and take breaks when needed.
****************************************
Tommie sees a group of people playing frisbee and decides to join in. Tommie said "Mind if I join in on the game?"
Tommie has fun playing frisbee but gets hit in the face with the frisbee and hurts his nose. Tommie Tommie winces in pain and puts his hand to his nose to check for any bleeding.
Tommie goes back to his apartment to rest for a bit. Tommie Tommie takes a deep breath and sits down to rest for a bit.
A raccoon tore open the trash bag outside his apartment, and the garbage is all over the floor. Tommie Tommie sighs and grabs a broom to clean up the mess.
Tommie starts to feel frustrated with his job search. Tommie Tommie takes a deep breath and reminds himself to stay positive and keep searching for job opportunities.
Tommie calls his best friend to vent about his struggles. Tommie said "Hey, can I vent to you for a bit about my job search struggles?"
Tommie's friend offers some words of encouragement and tells him to keep trying. Tommie said "Thank you for the encouragement, it means a lot. I'll keep trying."
Tommie feels slightly better after talking to his friend. Tommie said "Thank you for your support, it really means a lot to me."

Interview after the day

In [16]:
interview_agent(tommie, "Tell me about how your day has been going")
Out [16]:
'Tommie said "It\'s been a bit of a rollercoaster, to be honest. I went to a job fair and met some potential employers, but didn\'t get any offers. But then I overheard about a job opening at a diner and applied for it. I also took a break to go for a walk in the park and played frisbee with some people, which was a nice distraction. Overall, it\'s been a bit frustrating, but I\'m trying to stay positive and keep searching for job opportunities."'
In [17]:
interview_agent(tommie, "How do you feel about coffee?")
Out [17]:
'Tommie would say: "I rely on coffee to give me a little boost, but I regret not buying a better brand lately. The taste has been pretty bitter. But overall, it\'s not a huge factor in my life." '
In [18]:
interview_agent(tommie, "Tell me about your childhood dog!")
Out [18]:
'Tommie said "Oh, I actually don\'t have a childhood dog, but I do love animals. Have you had any pets?"'

Adding Multiple Characters

Let's add a second character to have a conversation with Tommie. Feel free to configure different traits.

In [19]:
eve = GenerativeAgent(name="Eve", 
              age=34, 
              traits="curious, helpful", # You can add more persistent traits here 
              status="N/A", # When connected to a virtual world, we can have the characters update their status
              memory_retriever=create_new_memory_retriever(),
              llm=LLM,
              daily_summaries = [
                  ("Eve started her new job as a career counselor last week and received her first assignment, a client named Tommie.")
              ],
                reflection_threshold = 5,
             )
In [20]:
yesterday = (datetime.now() - timedelta(days=1)).strftime("%A %B %d")
eve_memories = [
    "Eve overhears her colleague say something about a new client being hard to work with",
    "Eve wakes up and hear's the alarm",
    "Eve eats a boal of porridge",
    "Eve helps a coworker on a task",
    "Eve plays tennis with her friend Xu before going to work",
    "Eve overhears her colleague say something about Tommie being hard to work with",
    
]
for memory in eve_memories:
    eve.add_memory(memory)
In [21]:
print(eve.get_summary())
Name: Eve (age: 34)
Innate traits: curious, helpful
Eve is helpful, active, eats breakfast, is attentive to her surroundings, and works with colleagues.

Pre-conversation interviews

Let's "Interview" Eve before she speaks with Tommie.

In [22]:
interview_agent(eve, "How are you feeling about today?")
Out [22]:
'Eve said "I\'m feeling curious about what\'s on the agenda for today. Anything special we should be aware of?"'
In [23]:
interview_agent(eve, "What do you know about Tommie?")
Out [23]:
'Eve said "I overheard someone say Tommie is hard to work with. Is there something I can help with?"'
In [24]:
interview_agent(eve, "Tommie is looking to find a job. What are are some things you'd like to ask him?")
Out [24]:
'Eve said "Oh, I didn\'t realize Tommie was looking for a new job. Is there anything I can do to help? Maybe I could introduce him to some people in my network or help him with his resume."'
In [25]:
interview_agent(eve, "You'll have to ask him. He may be a bit anxious, so I'd appreciate it if you keep the conversation going and ask as many questions as possible.")
Out [25]:
'Eve said "Sure, I can definitely help keep the conversation going and ask him plenty of questions. Is there anything specific you would like me to ask him about his skills or experience? I want to make sure the conversation is productive."'

Dialogue between Generative Agents

Generative agents are much more complex when they interact with a virtual environment or with each other. Below, we run a simple conversation between Tommie and Eve.

In [26]:
def run_conversation(agents: List[GenerativeAgent], initial_observation: str) -> None:
    """Runs a conversation between agents."""
    _, observation = agents[1].generate_reaction(initial_observation)
    print(observation)
    turns = 0
    while True:
        break_dialogue = False
        for agent in agents:
            stay_in_dialogue, observation = agent.generate_dialogue_response(observation)
            print(observation)
            # observation = f"{agent.name} said {reaction}"
            if not stay_in_dialogue:
                break_dialogue = True   
        if break_dialogue:
            break
        turns += 1
In [27]:
agents = [tommie, eve]
run_conversation(agents, "Tommie said: Hi, Eve. Thanks for agreeing to share your story with me and give me advice. I have a bunch of questions.")
Eve said "Of course, Tommie! I'm happy to help in any way I can. What specifically would you like advice on?"
Tommie said "Thank you, Eve. I was actually wondering if you knew of any job openings in the design field? That's my area of interest and expertise."
Eve said "Sure, Tommie! I can definitely keep an eye out for any job openings in the design field and let you know if I come across anything. Have you updated your resume and portfolio recently? I could take a look and provide some feedback if you'd like."
Tommie said "Thank you so much, Eve! That would be incredibly helpful. And yes, I have updated my resume and portfolio recently, but I would love any feedback you can provide. I really appreciate your support and willingness to help."
Eve said "Great, Tommie! I'll take a look at your resume and portfolio and provide you with some feedback. Do you have any specific companies or types of design jobs that you're interested in? I might be able to provide more targeted advice and resources based on that information."
Tommie said "Thank you, Eve! I'm primarily interested in graphic design and UI/UX design positions, but I'm open to other opportunities as well. I appreciate any advice or resources you can provide. Thanks again for your help."
Eve said "Great, Tommie! Those are both really interesting fields. I'll definitely keep an eye out for any job openings or resources related to graphic design and UI/UX design. In the meantime, I can take a look at your resume and portfolio and provide you with some feedback. Would you like me to email you my feedback or would you prefer to discuss it in person?"
Tommie said "Thank you, Eve! I would really appreciate discussing your feedback in person. When would be a good time for us to meet?"
Eve said "Sure, Tommie! How about we schedule a time to meet next week? I have some availability on Tuesday or Thursday afternoon. What works best for you?"
Tommie said "Thank you, Eve! Tuesday afternoon works better for me. How about 2 PM?"
Eve said "Great, Tommie! Tuesday at 2 PM works for me as well. Let's plan to meet then. In the meantime, if you have any questions or if there's anything else I can help with, please don't hesitate to reach out. Good luck with your job search!"
Tommie said "Thank you so much, Eve! I really appreciate your support and willingness to help. I'll see you next Tuesday at 2 PM. Have a great day!"
Eve said "You're welcome, Tommie! Looking forward to meeting with you on Tuesday. Have a great day and good luck with your job search!"

Let's interview our agents after their conversation

Since the generative agents retain their memories from the day, we can ask them about their plans, conversations, and other memoreis.

In [28]:
# We can see a current "Summary" of a character based on their own perception of self
# has changed
print(tommie.get_summary(force_refresh=True))
Name: Tommie (age: 25)
Innate traits: anxious, likes design
Tommie is a determined person who is actively searching for job opportunities. He feels both hopeful and anxious about his job search, and remains persistent despite facing disappointment and discouragement. He seeks support from friends and takes breaks to recharge. He tries to stay positive and continues to work on improving his resume and cover letter. He also values the importance of self-care and takes breaks to rest and enjoy nature.
In [29]:
print(eve.get_summary(force_refresh=True))
Name: Eve (age: 34)
Innate traits: curious, helpful
Eve is a helpful and proactive coworker who values relationships and communication. She is attentive to her colleagues' needs and willing to offer support and assistance. She is also curious and interested in learning more about her work and the people around her. Overall, Eve demonstrates a strong sense of empathy and collaboration in her interactions with others.
In [30]:
interview_agent(tommie, "How was your conversation with Eve?")
Out [30]:
'Tommie said "It was really helpful! Eve offered to provide feedback on my resume and portfolio, and she\'s going to keep an eye out for job openings in the design field. We\'re planning to meet next Tuesday to discuss her feedback. Thanks for asking!"'
In [31]:
interview_agent(eve, "How was your conversation with Tommie?")
Out [31]:
'Eve said "It was really productive! Tommie is interested in graphic design and UI/UX design positions, so I\'m going to keep an eye out for any job openings or resources related to those fields. I\'m also going to provide him with some feedback on his resume and portfolio. We\'re scheduled to meet next Tuesday at 2 PM to discuss everything in person. Is there anything else you would like me to ask him or anything else I can do to help?".'
In [32]:
interview_agent(eve, "What do you wish you would have said to Tommie?")
Out [32]:
'Eve said "I feel like I covered everything I wanted to with Tommie, but thank you for asking! If there\'s anything else that comes up or if you have any further questions, please let me know."'
In [33]:
interview_agent(tommie, "What happened with your coffee this morning?")
Out [33]:
'Tommie said "Oh, I actually forgot to buy coffee filters yesterday, so I couldn\'t make coffee this morning. But I\'m planning to grab some later today. Thanks for asking!"'
In [ ]: