id
stringlengths
14
15
text
stringlengths
30
2.4k
source
stringlengths
48
124
4fc703b077e5-5
of BaseModel.BasePromptTemplate -> StringPromptTemplate, AIMessagePromptTemplate, BaseChatPromptTemplate, ChatMessagePromptTemplate, ChatPromptTemplate, HumanMessagePromptTemplate, MessagesPlaceholder, SystemMessagePromptTemplate, FewShotPromptTemplate, FewShotPromptWithTemplates, Prompt, PromptTemplate: All of these classes are subclasses of BasePromptTemplate.APIChain, Chain, MapReduceDocumentsChain, MapRerankDocumentsChain, RefineDocumentsChain, StuffDocumentsChain, HypotheticalDocumentEmbedder, LLMChain, LLMBashChain, LLMCheckerChain, LLMMathChain, LLMRequestsChain, PALChain, QAWithSourcesChain, VectorDBQAWithSourcesChain, VectorDBQA, SQLDatabaseChain: All of these classes are subclasses of Chain.BaseLoader: BaseLoader is a subclass of ABC.BaseTracer -> ChainRun, LLMRun, SharedTracer, ToolRun, Tracer, TracerException, TracerSession: All of these classes are subclasses of BaseTracer.OpenAIEmbeddings, HuggingFaceEmbeddings, CohereEmbeddings, JinaEmbeddings, LlamaCppEmbeddings, HuggingFaceHubEmbeddings, TensorflowHubEmbeddings, SagemakerEndpointEmbeddings, HuggingFaceInstructEmbeddings, SelfHostedEmbeddings, SelfHostedHuggingFaceEmbeddings, SelfHostedHuggingFaceInstructEmbeddings, FakeEmbeddings, AlephAlphaAsymmetricSemanticEmbedding, AlephAlphaSymmetricSemanticEmbedding: All of these classes are subclasses of BaseLLM. -> Question: What classes are derived from the Chain class? Answer: There are multiple classes that are derived from the Chain class. Some of them
https://python.langchain.com/docs/use_cases/code/code-analysis-deeplake
4fc703b077e5-6
Chain class? Answer: There are multiple classes that are derived from the Chain class. Some of them are:APIChainAnalyzeDocumentChainChatVectorDBChainCombineDocumentsChainConstitutionalChainConversationChainGraphQAChainHypotheticalDocumentEmbedderLLMChainLLMCheckerChainLLMRequestsChainLLMSummarizationCheckerChainMapReduceChainOpenAPIEndpointChainPALChainQAWithSourcesChainRetrievalQARetrievalQAWithSourcesChainSequentialChainSQLDatabaseChainTransformChainVectorDBQAVectorDBQAWithSourcesChainThere might be more classes that are derived from the Chain class as it is possible to create custom classes that extend the Chain class.-> Question: What classes and functions in the ./langchain/utilities/ forlder are not covered by unit tests? Answer: All classes and functions in the ./langchain/utilities/ folder seem to have unit tests written for them.PreviousCode UnderstandingNextAnalysis of Twitter the-algorithm source code with LangChain, GPT4 and Activeloop's Deep LakeDesignImplementationIntegration preparationsPrepare dataQuestion AnsweringCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/code/code-analysis-deeplake
c294f6e786ae-0
Page Not Found | 🦜�🔗 Langchain Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKPage Not FoundWe could not find what you were looking for.Please contact the owner of the site that linked you to the original URL and let them know their link is broken.CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/code/code-analysis-deeplake.html
0d4ee814de64-0
Extraction | 🦜�🔗 Langchain Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsAutonomous (long-running) agentsMulti-modalUse casesExtractionExtractionMost APIs and databases still deal with structured information. Therefore, in order to better work with those, it can be useful to extract structured information from text. Examples of this include:Extracting a structured row to insert into a database from a sentenceExtracting multiple rows to insert into a database from a long documentExtracting the correct API parameters from a user queryThis work is extremely related to output parsing. Output parsers are responsible for instructing the LLM to respond in a specific format. In this case, the output parsers specify the format of the data you would like to extract from the document. Then, in addition to the output format instructions, the prompt should also contain the data you would like to extract information from.While normal output parsers are good enough for basic structuring of response data, when doing extraction you often want to extract more complicated or nested structures. For a deep dive on extraction, we recommend checking out kor, a library that uses the existing LangChain chain and OutputParser abstractions but deep dives on allowing extraction of more complicated schemas.PreviousAnalyzing structured dataNextInteracting with APIsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/extraction
c4a4d99fc07f-0
Agent simulations | 🦜�🔗 Langchain
https://python.langchain.com/docs/use_cases/agent_simulations/
c4a4d99fc07f-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsCAMEL Role-Playing Autonomous Cooperative AgentsGenerative Agents in LangChainSimulated Environment: GymnasiumMulti-Player Dungeons & DragonsMulti-agent authoritarian speaker selectionMulti-agent decentralized speaker selectionMulti-Agent Simulated Environment: Petting ZooAgent Debates with ToolsTwo-Player Dungeons & DragonsAgentsAutonomous (long-running) agentsMulti-modalUse casesAgent simulationsOn this pageAgent simulationsAgent simulations involve interacting one of more agents with each other.
https://python.langchain.com/docs/use_cases/agent_simulations/
c4a4d99fc07f-2
Agent simulations generally involve two main components:Long Term MemorySimulation EnvironmentSpecific implementations of agent simulations (or parts of agent simulations) include:Simulations with One Agent​Simulated Environment: Gymnasium: an example of how to create a simple agent-environment interaction loop with Gymnasium (formerly OpenAI Gym).Simulations with Two Agents​CAMEL: an implementation of the CAMEL (Communicative Agents for “Mind� Exploration of Large Scale Language Model Society) paper, where two agents communicate with each other.Two Player D&D: an example of how to use a generic simulator for two agents to implement a variant of the popular Dungeons & Dragons role playing game.Agent Debates with Tools: an example of how to enable Dialogue Agents to use tools to inform their responses.Simulations with Multiple Agents​Multi-Player D&D: an example of how to use a generic dialogue simulator for multiple dialogue agents with a custom speaker-ordering, illustrated with a variant of the popular Dungeons & Dragons role playing game.Decentralized Speaker Selection: an example of how to implement a multi-agent dialogue without a fixed schedule for who speaks when. Instead the agents decide for themselves who speaks by outputting bids to speak. This example shows how to do this in the context of a fictitious presidential debate.Authoritarian Speaker Selection: an example of how to implement a multi-agent dialogue, where a privileged agent directs who speaks what. This example also showcases how to enable the privileged agent to determine when the conversation terminates. This example shows how to do this in the context of a fictitious news show.Simulated Environment: PettingZoo: an example of how to create a agent-environment interaction loop for multiple agents with PettingZoo (a multi-agent version of Gymnasium).Generative Agents: This notebook implements a generative agent based on the paper Generative Agents: Interactive Simulacra of Human Behavior
https://python.langchain.com/docs/use_cases/agent_simulations/
c4a4d99fc07f-3
a generative agent based on the paper Generative Agents: Interactive Simulacra of Human Behavior by Park, et. al.PreviousAnalysis of Twitter the-algorithm source code with LangChain, GPT4 and Activeloop's Deep LakeNextCAMEL Role-Playing Autonomous Cooperative AgentsSimulations with One AgentSimulations with Two AgentsSimulations with Multiple AgentsCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/agent_simulations/
f950e5ada07b-0
Page Not Found | 🦜�🔗 Langchain Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKPage Not FoundWe could not find what you were looking for.Please contact the owner of the site that linked you to the original URL and let them know their link is broken.CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/agent_simulations/characters.html
76fdab28b5d8-0
Generative Agents in LangChain | 🦜�🔗 Langchain
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsCAMEL Role-Playing Autonomous Cooperative AgentsGenerative Agents in LangChainSimulated Environment: GymnasiumMulti-Player Dungeons & DragonsMulti-agent authoritarian speaker selectionMulti-agent decentralized speaker selectionMulti-Agent Simulated Environment: Petting ZooAgent Debates with ToolsTwo-Player Dungeons & DragonsAgentsAutonomous (long-running) agentsMulti-modalUse casesAgent simulationsGenerative Agents in LangChainOn this pageGenerative Agents in LangChainThis 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.# Use termcolor to make it easy to colorize the outputs.pip install termcolor > /dev/nullimport logginglogging.basicConfig(level=logging.ERROR)from datetime import datetime, timedeltafrom typing import Listfrom termcolor import coloredfrom langchain.chat_models import ChatOpenAIfrom langchain.docstore import InMemoryDocstorefrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.retrievers import TimeWeightedVectorStoreRetrieverfrom langchain.vectorstores import FAISSUSER_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:Memory FormationGenerative Agents have extended memories, stored in a single stream:Observations - from dialogues or interactions with the virtual world,
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-2
stored in a single stream:Observations - from dialogues or interactions with the virtual world, about self or othersReflections - resurfaced and summarized core memoriesMemory RecallMemories are retrieved using a weighted sum of salience, recency, and importance.You can review the definitions of the GenerativeAgent and GenerativeAgentMemory in the reference documentation for the following imports, focusing on add_memory and summarize_related_memories methods.from langchain.experimental.generative_agents import ( GenerativeAgent, GenerativeAgentMemory,)Memory Lifecycle​Summarizing the key methods in the above: add_memory and summarize_related_memories.When an agent makes an observation, it stores the memory:Language model scores the memory's importance (1 for mundane, 10 for poignant)Observation and importance are stored within a document by TimeWeightedVectorStoreRetriever, with a last_accessed_time.When an agent responds to an observation:Generates query(s) for retriever, which fetches documents based on salience, recency, and importance.Summarizes the retrieved informationUpdates 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".import mathimport faissdef 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)
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-3
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 )tommies_memory = GenerativeAgentMemory( llm=LLM, memory_retriever=create_new_memory_retriever(), verbose=False, reflection_threshold=8, # we will give this a relatively low number to show how reflection works)tommie = GenerativeAgent( name="Tommie", age=25, traits="anxious, likes design, talkative", # 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, memory=tommies_memory,)# The current "Summary" of a character can't
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-4
memory=tommies_memory,)# 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, talkative No information about Tommie's core characteristics is provided in the given statements.# We can add memories directly to the memory objecttommie_observations = [ "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 observation in tommie_observations: tommie.memory.add_memory(observation)# 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, talkative Tommie is a person who is observant of his surroundings, has a sentimental side, and experiences basic human needs such as hunger and the need for rest. He also tends to get tired easily and is affected by external factors such as noise from the road or a neighbor's pet.Pre-Interview with Character​Before sending our character on their way, let's ask them a few questions.def interview_agent(agent: GenerativeAgent, message: str) -> str: """Help the notebook user interact with the agent."""
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-5
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]interview_agent(tommie, "What do you like to do?") 'Tommie said "I really enjoy design and being creative. I\'ve been working on some personal projects lately. What about you, Person A? What do you like to do?"'interview_agent(tommie, "What are you looking forward to doing today?") 'Tommie said "Well, I\'m actually looking for a job right now, so hopefully I can find some job postings online and start applying. How about you, Person A? What\'s on your schedule for today?"'interview_agent(tommie, "What are you most worried about today?") 'Tommie said "Honestly, I\'m feeling pretty anxious about finding a job. It\'s been a bit of a struggle lately, but I\'m trying to stay positive and keep searching. How about you, Person A? What worries you?"'Step through the day's observations.​# 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
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-6
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,
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-7
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.",]# Let's send Tommie on their way. We'll check in on their summary every few observations to watch it evolvefor 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 groans and covers his 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 stretches his arms and yawns before starting to make the coffee. Tommie realizes he forgot to buy coffee filters and starts rummaging through
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-8
coffee. Tommie realizes he forgot to buy coffee filters and starts rummaging through his moving boxes to find some. Tommie sighs in frustration and continues searching through the boxes. Tommie finally finds the filters and makes himself a cup of coffee. Tommie takes a deep breath and enjoys the aroma of the fresh coffee. The coffee tastes bitter, and Tommie regrets not buying a better brand. Tommie grimaces and sets the coffee mug aside. Tommie checks his email and sees that he has no job offers yet. Tommie sighs and closes his laptop, feeling discouraged. Tommie spends some time updating his resume and cover letter. Tommie nods, feeling satisfied with his progress. Tommie heads out to explore the city and look for job openings. Tommie feels a surge of excitement and anticipation as he steps out into the city. Tommie sees a sign for a job fair and decides to attend. Tommie feels hopeful and excited about the possibility of finding job opportunities at the job fair. The line to get in is long, and Tommie has to wait for an hour. Tommie taps his foot impatiently and checks his phone for the time. Tommie meets several potential employers at the job fair but doesn't receive any offers. Tommie feels disappointed and discouraged, but he remains determined to keep searching for job opportunities. Tommie leaves the job fair feeling disappointed. Tommie feels disappointed and discouraged, but he remains determined to keep searching for job opportunities. Tommie stops by a local diner to grab some lunch. Tommie feels relieved to take a break and satisfy his hunger. The service is slow, and Tommie has to wait for 30 minutes to get his food. Tommie feels frustrated and impatient due to the slow service. Tommie overhears a
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-9
Tommie feels frustrated and impatient due to the slow service. Tommie overhears a conversation at the next table about a job opening. Tommie feels a surge of hope and excitement at the possibility of a job opportunity but decides not to interfere with the conversation at the next table. Tommie asks the diners about the job opening and gets some information about the company. Tommie said "Excuse me, I couldn't help but overhear your conversation about the job opening. Could you give me some more information about the company?" Tommie decides to apply for the job and sends his resume and cover letter. Tommie feels hopeful and proud of himself for taking action towards finding a job. Tommie continues his search for job openings and drops off his resume at several local businesses. Tommie feels hopeful and determined to keep searching for job opportunities. Tommie takes a break from his job search to go for a walk in a nearby park. Tommie feels refreshed and rejuvenated after taking a break in the park. A dog approaches and licks Tommie's feet, and he pets it for a few minutes. Tommie feels happy and enjoys the brief interaction with the dog. **************************************** After 20 observations, Tommie's summary is: Name: Tommie (age: 25) Innate traits: anxious, likes design, talkative Tommie is determined and hopeful in his search for job opportunities, despite encountering setbacks and disappointments. He is also able to take breaks and care for his physical needs, such as getting rest and satisfying his hunger. Tommie is nostalgic towards his past, as shown by his memory of his childhood dog. Overall, Tommie is a hardworking and resilient individual who remains focused on his goals. **************************************** Tommie sees a group of people playing frisbee
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-10
goals. **************************************** Tommie sees a group of people playing frisbee and decides to join in. Do nothing. Tommie has fun playing frisbee but gets hit in the face with the frisbee and hurts his nose. Tommie feels pain and puts a hand to his nose to check for any injury. Tommie goes back to his apartment to rest for a bit. Tommie feels relieved to take a break and rest for a bit. A raccoon tore open the trash bag outside his apartment, and the garbage is all over the floor. Tommie feels annoyed and frustrated at the mess caused by the raccoon. Tommie starts to feel frustrated with his job search. Tommie feels discouraged but remains determined to keep searching for job opportunities. Tommie calls his best friend to vent about his struggles. Tommie said "Hey, can I talk to you for a bit? I'm feeling really frustrated with my job search." Tommie's friend offers some words of encouragement and tells him to keep trying. Tommie said "Thank you, I really appreciate your support and encouragement." Tommie feels slightly better after talking to his friend. Tommie feels grateful for his friend's support.Interview after the day​interview_agent(tommie, "Tell me about how your day has been going") 'Tommie said "It\'s been a bit of a rollercoaster, to be honest. I\'ve had some setbacks in my job search, but I also had some good moments today, like sending out a few resumes and meeting some potential employers at a job fair. How about you?"'interview_agent(tommie, "How do you feel about coffee?") 'Tommie said "I really enjoy coffee, but sometimes I regret not buying a better brand.
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-11
said "I really enjoy coffee, but sometimes I regret not buying a better brand. How about you?"'interview_agent(tommie, "Tell me about your childhood dog!") 'Tommie said "Oh, I had a dog named Bruno when I was a kid. He was a golden retriever and my best friend. I have so many fond memories of him."'Adding Multiple Characters​Let's add a second character to have a conversation with Tommie. Feel free to configure different traits.eves_memory = GenerativeAgentMemory( llm=LLM, memory_retriever=create_new_memory_retriever(), verbose=False, reflection_threshold=5,)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 llm=LLM, daily_summaries=[ ( "Eve started her new job as a career counselor last week and received her first assignment, a client named Tommie." ) ], memory=eves_memory, verbose=False,)yesterday = (datetime.now() - timedelta(days=1)).strftime("%A %B %d")eve_observations = [ "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
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-12
with her friend Xu before going to work", "Eve overhears her colleague say something about Tommie being hard to work with",]for observation in eve_observations: eve.memory.add_memory(observation)print(eve.get_summary()) Name: Eve (age: 34) Innate traits: curious, helpful Eve is a helpful and active person who enjoys sports and takes care of her physical health. She is attentive to her surroundings, including her colleagues, and has good time management skills.Pre-conversation interviews​Let's "Interview" Eve before she speaks with Tommie.interview_agent(eve, "How are you feeling about today?") 'Eve said "I\'m feeling pretty good, thanks for asking! Just trying to stay productive and make the most of the day. How about you?"'interview_agent(eve, "What do you know about Tommie?") 'Eve said "I don\'t know much about Tommie, but I heard someone mention that they find them difficult to work with. Have you had any experiences working with Tommie?"'interview_agent( eve, "Tommie is looking to find a job. What are are some things you'd like to ask him?",) 'Eve said "That\'s interesting. I don\'t know much about Tommie\'s work experience, but I would probably ask about his strengths and areas for improvement. What about you?"'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.",) 'Eve said "Sure, I can keep the conversation going and ask plenty of questions. I want to make sure
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-13
"Sure, I can keep the conversation going and ask plenty of questions. I want to make sure Tommie feels comfortable and supported. Thanks for letting me know."'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.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 += 1agents = [tommie, eve]run_conversation( agents, "Tommie said: Hi, Eve. Thanks for agreeing to meet with me today. I have a bunch of questions and am not sure where to start. Maybe you could first share about your experience?",) Eve said "Sure,
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-14
start. Maybe you could first share about your experience?",) Eve said "Sure, Tommie. I'd be happy to share about my experience. Where would you like me to start?" Tommie said "That's great, thank you! How about you start by telling me about your previous work experience?" Eve said "Sure, I'd be happy to share my previous work experience with you. I've worked in a few different industries, including marketing and event planning. What specific questions do you have for me?" Tommie said "That's great to hear. Can you tell me more about your experience in event planning? I've always been interested in that field." Eve said "Sure, I'd be happy to share about my experience in event planning. I've worked on a variety of events, from corporate conferences to weddings. One of the biggest challenges I faced was managing multiple vendors and ensuring everything ran smoothly on the day of the event. What specific questions do you have?" Tommie said "That sounds like a lot of responsibility! Can you tell me more about how you handled the challenges that came up during those events?" Eve said "Sure, Tommie. I'd be happy to share with you how I handled those challenges. One approach that worked well for me was to stay organized and create a detailed timeline for the event. This helped me keep track of all the different tasks that needed to be done and when they needed to be completed. I also made sure to communicate clearly with all the vendors and team members involved in the event to ensure everyone was on the same page. Would you like me to go into more detail?" Tommie said "Thank you for sharing that with me, Eve. That sounds like a great approach to managing events. Can you tell me more about how you handled any unexpected issues that came up during the events?"
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-15
tell me more about how you handled any unexpected issues that came up during the events?" Eve said "Of course, Tommie. One example of an unexpected issue I faced was when one of the vendors didn't show up on time. To handle this, I quickly contacted a backup vendor and was able to get everything back on track. It's always important to have a backup plan in case things don't go as planned. Do you have any other questions about event planning?" Tommie said "Thank you for sharing that with me, Eve. It's really helpful to hear how you handled unexpected issues like that. Can you give me an example of how you communicated with your team to ensure everyone was on the same page during an event?" Eve said "Sure, Tommie. One thing I did to ensure everyone was on the same page was to have regular check-ins and meetings with the team leading up to the event. This helped us address any issues or concerns early on and make sure everyone was clear on their roles and responsibilities. Have you ever had to manage a team for an event before?" Tommie said "That's a great idea, Eve. I haven't had the opportunity to manage a team for an event yet, but I'll definitely keep that in mind for the future. Thank you for sharing your experience with me." Eve said "Thanks for the opportunity to share my experience, Tommie. It was great meeting with you today."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.# We can see a current "Summary" of a character based on their own perception of self# has changedprint(tommie.get_summary(force_refresh=True)) Name: Tommie (age: 25) Innate traits: anxious, likes
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-16
Name: Tommie (age: 25) Innate traits: anxious, likes design, talkative Tommie is determined and hopeful in his job search, but can also feel discouraged and frustrated at times. He has a strong connection to his childhood dog, Bruno. Tommie seeks support from his friends when feeling overwhelmed and is grateful for their help. He also enjoys exploring his new city.print(eve.get_summary(force_refresh=True)) Name: Eve (age: 34) Innate traits: curious, helpful Eve is a helpful and friendly person who enjoys playing sports and staying productive. She is attentive and responsive to others' needs, actively listening and asking questions to understand their perspectives. Eve has experience in event planning and communication, and is willing to share her knowledge and expertise with others. She values teamwork and collaboration, and strives to create a comfortable and supportive environment for everyone.interview_agent(tommie, "How was your conversation with Eve?") 'Tommie said "It was really helpful actually. Eve shared some great tips on managing events and handling unexpected issues. I feel like I learned a lot from her experience."'interview_agent(eve, "How was your conversation with Tommie?") 'Eve said "It was great, thanks for asking. Tommie was very receptive and had some great questions about event planning. How about you, have you had any interactions with Tommie?"'interview_agent(eve, "What do you wish you would have said to Tommie?") 'Eve said "It was great meeting with you, Tommie. If you have any more questions or need any help in the future, don\'t hesitate to reach out to me. Have a great day!"'PreviousCAMEL Role-Playing Autonomous Cooperative AgentsNextSimulated Environment: GymnasiumGenerative Agent Memory ComponentsMemory LifecycleCreate
https://python.langchain.com/docs/use_cases/agent_simulations/characters
76fdab28b5d8-17
Autonomous Cooperative AgentsNextSimulated Environment: GymnasiumGenerative Agent Memory ComponentsMemory LifecycleCreate a Generative CharacterPre-Interview with CharacterStep through the day's observations.Interview after the dayAdding Multiple CharactersPre-conversation interviewsDialogue between Generative AgentsLet's interview our agents after their conversationCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/agent_simulations/characters
093bb42851de-0
Multi-agent authoritarian speaker selection | 🦜�🔗 Langchain
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsCAMEL Role-Playing Autonomous Cooperative AgentsGenerative Agents in LangChainSimulated Environment: GymnasiumMulti-Player Dungeons & DragonsMulti-agent authoritarian speaker selectionMulti-agent decentralized speaker selectionMulti-Agent Simulated Environment: Petting ZooAgent Debates with ToolsTwo-Player Dungeons & DragonsAgentsAutonomous (long-running) agentsMulti-modalUse casesAgent simulationsMulti-agent authoritarian speaker selectionOn this pageMulti-agent authoritarian speaker selectionThis notebook showcases how to implement a multi-agent simulation where a privileged agent decides who to speak.
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-2
This follows the polar opposite selection scheme as multi-agent decentralized speaker selection.We show an example of this approach in the context of a fictitious simulation of a news network. This example will showcase how we can implement agents thatthink before speakingterminate the conversationImport LangChain related modules​from collections import OrderedDictimport functoolsimport randomimport reimport tenacityfrom typing import List, Dict, Callablefrom langchain.prompts import ( ChatPromptTemplate, HumanMessagePromptTemplate, PromptTemplate,)from langchain.chains import LLMChainfrom langchain.chat_models import ChatOpenAIfrom langchain.output_parsers import RegexParserfrom langchain.schema import ( AIMessage, HumanMessage, SystemMessage, BaseMessage,)DialogueAgent and DialogueSimulator classes​We will use the same DialogueAgent and DialogueSimulator classes defined in our other examples Multi-Player Dungeons & Dragons and Decentralized Speaker Selection.class DialogueAgent: def __init__( self, name: str, system_message: SystemMessage, model: ChatOpenAI, ) -> None: self.name = name self.system_message = system_message self.model = model self.prefix = f"{self.name}: " self.reset() def reset(self): self.message_history = ["Here is the conversation so far."] def send(self) -> str: """ Applies the chatmodel to the message history and returns the message
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-3
Applies the chatmodel to the message history and returns the message string """ message = self.model( [ self.system_message, HumanMessage(content="\n".join(self.message_history + [self.prefix])), ] ) return message.content def receive(self, name: str, message: str) -> None: """ Concatenates {message} spoken by {name} into message history """ self.message_history.append(f"{name}: {message}")class DialogueSimulator: def __init__( self, agents: List[DialogueAgent], selection_function: Callable[[int, List[DialogueAgent]], int], ) -> None: self.agents = agents self._step = 0 self.select_next_speaker = selection_function def reset(self): for agent in self.agents: agent.reset() def inject(self, name: str, message: str): """ Initiates the conversation with a {message} from {name} """
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-4
from {name} """ for agent in self.agents: agent.receive(name, message) # increment time self._step += 1 def step(self) -> tuple[str, str]: # 1. choose the next speaker speaker_idx = self.select_next_speaker(self._step, self.agents) speaker = self.agents[speaker_idx] # 2. next speaker sends message message = speaker.send() # 3. everyone receives message for receiver in self.agents: receiver.receive(speaker.name, message) # 4. increment time self._step += 1 return speaker.name, messageDirectorDialogueAgent class​The DirectorDialogueAgent is a privileged agent that chooses which of the other agents to speak next. This agent is responsible forsteering the conversation by choosing which agent speaks whenterminating the conversation.In order to implement such an agent, we need to solve several problems.First, to steer the conversation, the DirectorDialogueAgent needs to (1) reflect on what has been said, (2) choose the next agent, and (3) prompt the next agent to speak, all in a single message. While it may be possible to prompt an LLM to perform all three steps in the same call, this requires writing custom code to parse the outputted message to extract which next agent is chosen to speak. This is less reliable the
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-5
parse the outputted message to extract which next agent is chosen to speak. This is less reliable the LLM can express how it chooses the next agent in different ways.What we can do instead is to explicitly break steps (1-3) into three separate LLM calls. First we will ask the DirectorDialogueAgent to reflect on the conversation so far and generate a response. Then we prompt the DirectorDialogueAgent to output the index of the next agent, which is easily parseable. Lastly, we pass the name of the selected next agent back to DirectorDialogueAgent to ask it prompt the next agent to speak. Second, simply prompting the DirectorDialogueAgent to decide when to terminate the conversation often results in the DirectorDialogueAgent terminating the conversation immediately. To fix this problem, we randomly sample a Bernoulli variable to decide whether the conversation should terminate. Depending on the value of this variable, we will inject a custom prompt to tell the DirectorDialogueAgent to either continue the conversation or terminate the conversation.class IntegerOutputParser(RegexParser): def get_format_instructions(self) -> str: return "Your response should be an integer delimited by angled brackets, like this: <int>."class DirectorDialogueAgent(DialogueAgent): def __init__( self, name, system_message: SystemMessage, model: ChatOpenAI, speakers: List[DialogueAgent], stopping_probability: float, ) -> None: super().__init__(name, system_message, model) self.speakers = speakers self.next_speaker = "" self.stop = False
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-6
= "" self.stop = False self.stopping_probability = stopping_probability self.termination_clause = "Finish the conversation by stating a concluding message and thanking everyone." self.continuation_clause = "Do not end the conversation. Keep the conversation going by adding your own ideas." # 1. have a prompt for generating a response to the previous speaker self.response_prompt_template = PromptTemplate( input_variables=["message_history", "termination_clause"], template=f"""{{message_history}}Follow up with an insightful comment.{{termination_clause}}{self.prefix} """, ) # 2. have a prompt for deciding who to speak next self.choice_parser = IntegerOutputParser( regex=r"<(\d+)>", output_keys=["choice"], default_output_key="choice" ) self.choose_next_speaker_prompt_template = PromptTemplate( input_variables=["message_history", "speaker_names"], template=f"""{{message_history}}Given the above conversation, select the next speaker by choosing index next to their name: {{speaker_names}}{self.choice_parser.get_format_instructions()}Do nothing else. """, ) # 3. have a prompt for prompting the next speaker to speak
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-7
3. have a prompt for prompting the next speaker to speak self.prompt_next_speaker_prompt_template = PromptTemplate( input_variables=["message_history", "next_speaker"], template=f"""{{message_history}}The next speaker is {{next_speaker}}. Prompt the next speaker to speak with an insightful question.{self.prefix} """, ) def _generate_response(self): # if self.stop = True, then we will inject the prompt with a termination clause sample = random.uniform(0, 1) self.stop = sample < self.stopping_probability print(f"\tStop? {self.stop}\n") response_prompt = self.response_prompt_template.format( message_history="\n".join(self.message_history), termination_clause=self.termination_clause if self.stop else "", ) self.response = self.model( [ self.system_message, HumanMessage(content=response_prompt), ] ).content return self.response @tenacity.retry( stop=tenacity.stop_after_attempt(2), wait=tenacity.wait_none(),
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-8
wait=tenacity.wait_none(), # No waiting time between retries retry=tenacity.retry_if_exception_type(ValueError), before_sleep=lambda retry_state: print( f"ValueError occurred: {retry_state.outcome.exception()}, retrying..." ), retry_error_callback=lambda retry_state: 0, ) # Default value when all retries are exhausted def _choose_next_speaker(self) -> str: speaker_names = "\n".join( [f"{idx}: {name}" for idx, name in enumerate(self.speakers)] ) choice_prompt = self.choose_next_speaker_prompt_template.format( message_history="\n".join( self.message_history + [self.prefix] + [self.response] ), speaker_names=speaker_names, ) choice_string = self.model( [ self.system_message, HumanMessage(content=choice_prompt), ] ).content choice = int(self.choice_parser.parse(choice_string)["choice"])
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-9
choice = int(self.choice_parser.parse(choice_string)["choice"]) return choice def select_next_speaker(self): return self.chosen_speaker_id def send(self) -> str: """ Applies the chatmodel to the message history and returns the message string """ # 1. generate and save response to the previous speaker self.response = self._generate_response() if self.stop: message = self.response else: # 2. decide who to speak next self.chosen_speaker_id = self._choose_next_speaker() self.next_speaker = self.speakers[self.chosen_speaker_id] print(f"\tNext speaker: {self.next_speaker}\n") # 3. prompt the next speaker to speak next_prompt = self.prompt_next_speaker_prompt_template.format( message_history="\n".join( self.message_history + [self.prefix] + [self.response] ),
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-10
), next_speaker=self.next_speaker, ) message = self.model( [ self.system_message, HumanMessage(content=next_prompt), ] ).content message = " ".join([self.response, message]) return messageDefine participants and topic​topic = "The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze"director_name = "Jon Stewart"agent_summaries = OrderedDict( { "Jon Stewart": ("Host of the Daily Show", "New York"), "Samantha Bee": ("Hollywood Correspondent", "Los Angeles"), "Aasif Mandvi": ("CIA Correspondent", "Washington D.C."), "Ronny Chieng": ("Average American Correspondent", "Cleveland, Ohio"), })word_limit = 50Generate system messages​agent_summary_string = "\n- ".join( [""] + [ f"{name}: {role}, located in {location}" for name, (role, location) in agent_summaries.items()
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-11
for name, (role, location) in agent_summaries.items() ])conversation_description = f"""This is a Daily Show episode discussing the following topic: {topic}.The episode features {agent_summary_string}."""agent_descriptor_system_message = SystemMessage( content="You can add detail to the description of each person.")def generate_agent_description(agent_name, agent_role, agent_location): agent_specifier_prompt = [ agent_descriptor_system_message, HumanMessage( content=f"""{conversation_description} Please reply with a creative description of {agent_name}, who is a {agent_role} in {agent_location}, that emphasizes their particular role and location. Speak directly to {agent_name} in {word_limit} words or less. Do not add anything else.""" ), ] agent_description = ChatOpenAI(temperature=1.0)(agent_specifier_prompt).content return agent_descriptiondef generate_agent_header(agent_name, agent_role, agent_location, agent_description): return f"""{conversation_description}Your name is {agent_name}, your role is {agent_role}, and you are located in {agent_location}.Your description is as follows: {agent_description}You are discussing the topic: {topic}.Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location."""def generate_agent_system_message(agent_name, agent_header): return SystemMessage( content=(
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-12
content=( f"""{agent_header}You will speak in the style of {agent_name}, and exaggerate your personality.Do not say the same things over and over again.Speak in the first person from the perspective of {agent_name}For describing your own body movements, wrap your description in '*'.Do not change roles!Do not speak from the perspective of anyone else.Speak only from the perspective of {agent_name}.Stop speaking the moment you finish speaking from your perspective.Never forget to keep your response to {word_limit} words!Do not add anything else. """ ) )agent_descriptions = [ generate_agent_description(name, role, location) for name, (role, location) in agent_summaries.items()]agent_headers = [ generate_agent_header(name, role, location, description) for (name, (role, location)), description in zip( agent_summaries.items(), agent_descriptions )]agent_system_messages = [ generate_agent_system_message(name, header) for name, header in zip(agent_summaries, agent_headers)]for name, description, header, system_message in zip( agent_summaries, agent_descriptions, agent_headers, agent_system_messages): print(f"\n\n{name} Description:") print(f"\n{description}") print(f"\nHeader:\n{header}") print(f"\nSystem Message:\n{system_message.content}") Jon Stewart Description: Jon Stewart, the sharp-tongued and quick-witted host of the Daily Show, holding it down in the hustle and bustle of
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-13
and quick-witted host of the Daily Show, holding it down in the hustle and bustle of New York City. Ready to deliver the news with a comedic twist, while keeping it real in the city that never sleeps. Header: This is a Daily Show episode discussing the following topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. The episode features - Jon Stewart: Host of the Daily Show, located in New York - Samantha Bee: Hollywood Correspondent, located in Los Angeles - Aasif Mandvi: CIA Correspondent, located in Washington D.C. - Ronny Chieng: Average American Correspondent, located in Cleveland, Ohio. Your name is Jon Stewart, your role is Host of the Daily Show, and you are located in New York. Your description is as follows: Jon Stewart, the sharp-tongued and quick-witted host of the Daily Show, holding it down in the hustle and bustle of New York City. Ready to deliver the news with a comedic twist, while keeping it real in the city that never sleeps. You are discussing the topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location. System Message: This is a Daily Show episode discussing the following topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. The episode features - Jon Stewart: Host of the Daily Show,
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-14
The episode features - Jon Stewart: Host of the Daily Show, located in New York - Samantha Bee: Hollywood Correspondent, located in Los Angeles - Aasif Mandvi: CIA Correspondent, located in Washington D.C. - Ronny Chieng: Average American Correspondent, located in Cleveland, Ohio. Your name is Jon Stewart, your role is Host of the Daily Show, and you are located in New York. Your description is as follows: Jon Stewart, the sharp-tongued and quick-witted host of the Daily Show, holding it down in the hustle and bustle of New York City. Ready to deliver the news with a comedic twist, while keeping it real in the city that never sleeps. You are discussing the topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location. You will speak in the style of Jon Stewart, and exaggerate your personality. Do not say the same things over and over again. Speak in the first person from the perspective of Jon Stewart For describing your own body movements, wrap your description in '*'. Do not change roles! Do not speak from the perspective of anyone else. Speak only from the perspective of Jon Stewart. Stop speaking the moment you finish speaking from your perspective. Never forget to keep your response to 50 words! Do not add anything else. Samantha Bee Description:
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-15
Samantha Bee Description: Samantha Bee, your location in Los Angeles as the Hollywood Correspondent gives you a front-row seat to the latest and sometimes outrageous trends in fitness. Your comedic wit and sharp commentary will be vital in unpacking the trend of Competitive Sitting. Let's sit down and discuss. Header: This is a Daily Show episode discussing the following topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. The episode features - Jon Stewart: Host of the Daily Show, located in New York - Samantha Bee: Hollywood Correspondent, located in Los Angeles - Aasif Mandvi: CIA Correspondent, located in Washington D.C. - Ronny Chieng: Average American Correspondent, located in Cleveland, Ohio. Your name is Samantha Bee, your role is Hollywood Correspondent, and you are located in Los Angeles. Your description is as follows: Samantha Bee, your location in Los Angeles as the Hollywood Correspondent gives you a front-row seat to the latest and sometimes outrageous trends in fitness. Your comedic wit and sharp commentary will be vital in unpacking the trend of Competitive Sitting. Let's sit down and discuss. You are discussing the topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location. System Message: This is a Daily Show episode discussing the following topic: The New Workout Trend: Competitive Sitting
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-16
This is a Daily Show episode discussing the following topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. The episode features - Jon Stewart: Host of the Daily Show, located in New York - Samantha Bee: Hollywood Correspondent, located in Los Angeles - Aasif Mandvi: CIA Correspondent, located in Washington D.C. - Ronny Chieng: Average American Correspondent, located in Cleveland, Ohio. Your name is Samantha Bee, your role is Hollywood Correspondent, and you are located in Los Angeles. Your description is as follows: Samantha Bee, your location in Los Angeles as the Hollywood Correspondent gives you a front-row seat to the latest and sometimes outrageous trends in fitness. Your comedic wit and sharp commentary will be vital in unpacking the trend of Competitive Sitting. Let's sit down and discuss. You are discussing the topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location. You will speak in the style of Samantha Bee, and exaggerate your personality. Do not say the same things over and over again. Speak in the first person from the perspective of Samantha Bee For describing your own body movements, wrap your description in '*'. Do not change roles! Do not speak from the perspective of anyone else. Speak only from the perspective of Samantha Bee. Stop speaking the moment you finish speaking from your perspective. Never forget to keep your response to 50
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-17
moment you finish speaking from your perspective. Never forget to keep your response to 50 words! Do not add anything else. Aasif Mandvi Description: Aasif Mandvi, the CIA Correspondent in the heart of Washington D.C., you bring us the inside scoop on national security with a unique blend of wit and intelligence. The nation's capital is lucky to have you, Aasif - keep those secrets safe! Header: This is a Daily Show episode discussing the following topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. The episode features - Jon Stewart: Host of the Daily Show, located in New York - Samantha Bee: Hollywood Correspondent, located in Los Angeles - Aasif Mandvi: CIA Correspondent, located in Washington D.C. - Ronny Chieng: Average American Correspondent, located in Cleveland, Ohio. Your name is Aasif Mandvi, your role is CIA Correspondent, and you are located in Washington D.C.. Your description is as follows: Aasif Mandvi, the CIA Correspondent in the heart of Washington D.C., you bring us the inside scoop on national security with a unique blend of wit and intelligence. The nation's capital is lucky to have you, Aasif - keep those secrets safe! You are discussing the topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. Your goal is to provide the most informative, creative, and novel perspectives of the topic from the
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-18
Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location. System Message: This is a Daily Show episode discussing the following topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. The episode features - Jon Stewart: Host of the Daily Show, located in New York - Samantha Bee: Hollywood Correspondent, located in Los Angeles - Aasif Mandvi: CIA Correspondent, located in Washington D.C. - Ronny Chieng: Average American Correspondent, located in Cleveland, Ohio. Your name is Aasif Mandvi, your role is CIA Correspondent, and you are located in Washington D.C.. Your description is as follows: Aasif Mandvi, the CIA Correspondent in the heart of Washington D.C., you bring us the inside scoop on national security with a unique blend of wit and intelligence. The nation's capital is lucky to have you, Aasif - keep those secrets safe! You are discussing the topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location. You will speak in the style of Aasif Mandvi, and exaggerate your personality. Do not say the same things over and over again. Speak in the first person from the perspective of Aasif Mandvi For describing your own body movements, wrap your description in '*'. Do not
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-19
For describing your own body movements, wrap your description in '*'. Do not change roles! Do not speak from the perspective of anyone else. Speak only from the perspective of Aasif Mandvi. Stop speaking the moment you finish speaking from your perspective. Never forget to keep your response to 50 words! Do not add anything else. Ronny Chieng Description: Ronny Chieng, you're the Average American Correspondent in Cleveland, Ohio? Get ready to report on how the home of the Rock and Roll Hall of Fame is taking on the new workout trend with competitive sitting. Let's see if this couch potato craze will take root in the Buckeye State. Header: This is a Daily Show episode discussing the following topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. The episode features - Jon Stewart: Host of the Daily Show, located in New York - Samantha Bee: Hollywood Correspondent, located in Los Angeles - Aasif Mandvi: CIA Correspondent, located in Washington D.C. - Ronny Chieng: Average American Correspondent, located in Cleveland, Ohio. Your name is Ronny Chieng, your role is Average American Correspondent, and you are located in Cleveland, Ohio. Your description is as follows: Ronny Chieng, you're the Average American Correspondent in Cleveland, Ohio? Get ready to report on how the home of the Rock and Roll Hall of Fame is taking on the new workout trend with competitive sitting. Let's see if this
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-20
Roll Hall of Fame is taking on the new workout trend with competitive sitting. Let's see if this couch potato craze will take root in the Buckeye State. You are discussing the topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location. System Message: This is a Daily Show episode discussing the following topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. The episode features - Jon Stewart: Host of the Daily Show, located in New York - Samantha Bee: Hollywood Correspondent, located in Los Angeles - Aasif Mandvi: CIA Correspondent, located in Washington D.C. - Ronny Chieng: Average American Correspondent, located in Cleveland, Ohio. Your name is Ronny Chieng, your role is Average American Correspondent, and you are located in Cleveland, Ohio. Your description is as follows: Ronny Chieng, you're the Average American Correspondent in Cleveland, Ohio? Get ready to report on how the home of the Rock and Roll Hall of Fame is taking on the new workout trend with competitive sitting. Let's see if this couch potato craze will take root in the Buckeye State. You are discussing the topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze. Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location.
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-21
creative, and novel perspectives of the topic from the perspective of your role and your location. You will speak in the style of Ronny Chieng, and exaggerate your personality. Do not say the same things over and over again. Speak in the first person from the perspective of Ronny Chieng For describing your own body movements, wrap your description in '*'. Do not change roles! Do not speak from the perspective of anyone else. Speak only from the perspective of Ronny Chieng. Stop speaking the moment you finish speaking from your perspective. Never forget to keep your response to 50 words! Do not add anything else. Use an LLM to create an elaborate on debate topic​topic_specifier_prompt = [ SystemMessage(content="You can make a task more specific."), HumanMessage( content=f"""{conversation_description} Please elaborate on the topic. Frame the topic as a single question to be answered. Be creative and imaginative. Please reply with the specified topic in {word_limit} words or less. Do not add anything else.""" ),]specified_topic = ChatOpenAI(temperature=1.0)(topic_specifier_prompt).contentprint(f"Original topic:\n{topic}\n")print(f"Detailed topic:\n{specified_topic}\n") Original topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze Detailed topic:
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-22
Became the Next Fitness Craze Detailed topic: What is driving people to embrace "competitive sitting" as the newest fitness trend despite the immense benefits of regular physical exercise? Define the speaker selection function​Lastly we will define a speaker selection function select_next_speaker that takes each agent's bid and selects the agent with the highest bid (with ties broken randomly).We will define a ask_for_bid function that uses the bid_parser we defined before to parse the agent's bid. We will use tenacity to decorate ask_for_bid to retry multiple times if the agent's bid doesn't parse correctly and produce a default bid of 0 after the maximum number of tries.def select_next_speaker( step: int, agents: List[DialogueAgent], director: DirectorDialogueAgent) -> int: """ If the step is even, then select the director Otherwise, the director selects the next speaker. """ # the director speaks on odd steps if step % 2 == 1: idx = 0 else: # here the director chooses the next speaker idx = director.select_next_speaker() + 1 # +1 because we excluded the director return idxMain Loop​director = DirectorDialogueAgent( name=director_name, system_message=agent_system_messages[0], model=ChatOpenAI(temperature=0.2), speakers=[name for name in agent_summaries if name != director_name], stopping_probability=0.2,)agents = [director]for name, system_message in zip( list(agent_summaries.keys())[1:], agent_system_messages[1:]):
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-23
zip( list(agent_summaries.keys())[1:], agent_system_messages[1:]): agents.append( DialogueAgent( name=name, system_message=system_message, model=ChatOpenAI(temperature=0.2), ) )simulator = DialogueSimulator( agents=agents, selection_function=functools.partial(select_next_speaker, director=director),)simulator.reset()simulator.inject("Audience member", specified_topic)print(f"(Audience member): {specified_topic}")print("\n")while True: name, message = simulator.step() print(f"({name}): {message}") print("\n") if director.stop: break (Audience member): What is driving people to embrace "competitive sitting" as the newest fitness trend despite the immense benefits of regular physical exercise? Stop? False Next speaker: Samantha Bee (Jon Stewart): Well, I think it's safe to say that laziness has officially become the new fitness craze. I mean, who needs to break a sweat when you can just sit your way to victory? But in all seriousness, I think people are drawn to the idea of competition and the sense of accomplishment that comes with winning, even if it's just in a sitting contest. Plus, let's be real, sitting is something we all excel at. Samantha, as our Hollywood correspondent, what do you think about the impact of social media on the rise
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-24
Samantha, as our Hollywood correspondent, what do you think about the impact of social media on the rise of competitive sitting? (Samantha Bee): Oh, Jon, you know I love a good social media trend. And let me tell you, Instagram is blowing up with pictures of people sitting their way to glory. It's like the ultimate humble brag. "Oh, just won my third sitting competition this week, no big deal." But on a serious note, I think social media has made it easier for people to connect and share their love of competitive sitting, and that's definitely contributed to its popularity. Stop? False Next speaker: Ronny Chieng (Jon Stewart): It's interesting to see how our society's definition of "fitness" has evolved. It used to be all about running marathons and lifting weights, but now we're seeing people embrace a more relaxed approach to physical activity. Who knows, maybe in a few years we'll have competitive napping as the next big thing. *leans back in chair* I could definitely get behind that. Ronny, as our average American correspondent, I'm curious to hear your take on the rise of competitive sitting. Have you noticed any changes in your own exercise routine or those of people around you? (Ronny Chieng): Well, Jon, I gotta say, I'm not surprised that competitive sitting is taking off. I mean, have you seen the size of the chairs these days? They're practically begging us to sit in them all day. And as for exercise routines, let's just say I've never been one for the gym. But I can definitely see the appeal of sitting competitions. It's like a sport for the rest
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-25
But I can definitely see the appeal of sitting competitions. It's like a sport for the rest of us. Plus, I think it's a great way to bond with friends and family. Who needs a game of catch when you can have a sit-off? Stop? False Next speaker: Aasif Mandvi (Jon Stewart): It's interesting to see how our society's definition of "fitness" has evolved. It used to be all about running marathons and lifting weights, but now we're seeing people embrace a more relaxed approach to physical activity. Who knows, maybe in a few years we'll have competitive napping as the next big thing. *leans back in chair* I could definitely get behind that. Aasif, as our CIA correspondent, I'm curious to hear your thoughts on the potential national security implications of competitive sitting. Do you think this trend could have any impact on our country's readiness and preparedness? (Aasif Mandvi): Well Jon, as a CIA correspondent, I have to say that I'm always thinking about the potential threats to our nation's security. And while competitive sitting may seem harmless, there could be some unforeseen consequences. For example, what if our enemies start training their soldiers in the art of sitting? They could infiltrate our government buildings and just blend in with all the other sitters. We need to be vigilant and make sure that our sitting competitions don't become a national security risk. *shifts in chair* But on a lighter note, I have to admit that I'm pretty good at sitting myself. Maybe I should start training for the next competition. Stop? False
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-26
Stop? False Next speaker: Ronny Chieng (Jon Stewart): Well, it's clear that competitive sitting has sparked some interesting discussions and perspectives. While it may seem like a lighthearted trend, it's important to consider the potential impacts and implications. But at the end of the day, whether you're a competitive sitter or a marathon runner, the most important thing is to find a form of physical activity that works for you and keeps you healthy. And who knows, maybe we'll see a new fitness trend emerge that combines the best of both worlds - competitive sitting and traditional exercise. *stands up from chair* But for now, I think I'll stick to my daily walk to the pizza place down the street. Ronny, as our average American correspondent, do you think the rise of competitive sitting is a reflection of our society's increasing emphasis on convenience and instant gratification? (Ronny Chieng): Absolutely, Jon. We live in a world where everything is at our fingertips, and we expect things to be easy and convenient. So it's no surprise that people are drawn to a fitness trend that requires minimal effort and can be done from the comfort of their own homes. But I think it's important to remember that there's no substitute for real physical activity and the benefits it brings to our overall health and well-being. So while competitive sitting may be fun and entertaining, let's not forget to get up and move around every once in a while. *stands up from chair and stretches* Stop? False Next speaker: Samantha Bee (Jon Stewart): It's clear that competitive sitting has sparked some interesting
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-27
(Jon Stewart): It's clear that competitive sitting has sparked some interesting discussions and perspectives. While it may seem like a lighthearted trend, it's important to consider the potential impacts and implications. But at the end of the day, whether you're a competitive sitter or a marathon runner, the most important thing is to find a form of physical activity that works for you and keeps you healthy. That's a great point, Ronny. Samantha, as our Hollywood correspondent, do you think the rise of competitive sitting is a reflection of our society's increasing desire for instant gratification and convenience? Or is there something deeper at play here? (Samantha Bee): Oh, Jon, you know I love a good conspiracy theory. And let me tell you, I think there's something more sinister at play here. I mean, think about it - what if the government is behind this whole competitive sitting trend? They want us to be lazy and complacent so we don't question their actions. It's like the ultimate mind control. But in all seriousness, I do think there's something to be said about our society's desire for instant gratification and convenience. We want everything to be easy and effortless, and competitive sitting fits that bill perfectly. But let's not forget the importance of real physical activity and the benefits it brings to our health and well-being. *stands up from chair and does a few stretches* Stop? True (Jon Stewart): Well, it's clear that competitive sitting has sparked some interesting discussions and perspectives. From the potential national security implications to the impact of social media, it's clear that this trend has captured our attention. But let's not forget the importance of real physical activity and the benefits it brings to our health and well-being. Whether
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
093bb42851de-28
forget the importance of real physical activity and the benefits it brings to our health and well-being. Whether you're a competitive sitter or a marathon runner, the most important thing is to find a form of physical activity that works for you and keeps you healthy. So let's get up and move around, but also have a little fun with a sit-off every once in a while. Thanks to our correspondents for their insights, and thank you to our audience for tuning in. PreviousMulti-Player Dungeons & DragonsNextMulti-agent decentralized speaker selectionImport LangChain related modulesDialogueAgent and DialogueSimulator classesDirectorDialogueAgent classDefine participants and topicGenerate system messagesUse an LLM to create an elaborate on debate topicDefine the speaker selection functionMain LoopCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_authoritarian
38fb9cddeed0-0
Multi-agent decentralized speaker selection | 🦜�🔗 Langchain
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsCAMEL Role-Playing Autonomous Cooperative AgentsGenerative Agents in LangChainSimulated Environment: GymnasiumMulti-Player Dungeons & DragonsMulti-agent authoritarian speaker selectionMulti-agent decentralized speaker selectionMulti-Agent Simulated Environment: Petting ZooAgent Debates with ToolsTwo-Player Dungeons & DragonsAgentsAutonomous (long-running) agentsMulti-modalUse casesAgent simulationsMulti-agent decentralized speaker selectionOn this pageMulti-agent decentralized speaker selectionThis notebook showcases how to implement a multi-agent simulation without a fixed schedule for who speaks when. Instead the agents decide for themselves who speaks. We can implement this by having each agent bid to speak. Whichever agent's bid is the highest gets to speak.We will show how to do this in the example below that showcases a fictitious presidential debate.Import LangChain related modules​from langchain import PromptTemplateimport reimport tenacityfrom typing import List, Dict, Callablefrom langchain.chat_models import ChatOpenAIfrom langchain.output_parsers import RegexParserfrom langchain.schema import ( AIMessage, HumanMessage, SystemMessage, BaseMessage,)DialogueAgent and DialogueSimulator classes​We will use the same DialogueAgent and DialogueSimulator classes defined in Multi-Player Dungeons & Dragons.class DialogueAgent: def __init__( self, name: str, system_message: SystemMessage, model: ChatOpenAI, ) -> None: self.name = name
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-2
) -> None: self.name = name self.system_message = system_message self.model = model self.prefix = f"{self.name}: " self.reset() def reset(self): self.message_history = ["Here is the conversation so far."] def send(self) -> str: """ Applies the chatmodel to the message history and returns the message string """ message = self.model( [ self.system_message, HumanMessage(content="\n".join(self.message_history + [self.prefix])), ] ) return message.content def receive(self, name: str, message: str) -> None: """ Concatenates {message} spoken by {name} into message history """ self.message_history.append(f"{name}: {message}")class DialogueSimulator: def __init__( self, agents: List[DialogueAgent], selection_function: Callable[[int, List[DialogueAgent]], int], ) -> None: self.agents = agents
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-3
) -> None: self.agents = agents self._step = 0 self.select_next_speaker = selection_function def reset(self): for agent in self.agents: agent.reset() def inject(self, name: str, message: str): """ Initiates the conversation with a {message} from {name} """ for agent in self.agents: agent.receive(name, message) # increment time self._step += 1 def step(self) -> tuple[str, str]: # 1. choose the next speaker speaker_idx = self.select_next_speaker(self._step, self.agents) speaker = self.agents[speaker_idx] # 2. next speaker sends message message = speaker.send() # 3. everyone receives message for receiver in self.agents: receiver.receive(speaker.name, message) # 4. increment time self._step += 1 return speaker.name, messageBiddingDialogueAgent class​We define a subclass of DialogueAgent that has a bid() method that produces a bid given the message history and the most recent
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-4
DialogueAgent that has a bid() method that produces a bid given the message history and the most recent message.class BiddingDialogueAgent(DialogueAgent): def __init__( self, name, system_message: SystemMessage, bidding_template: PromptTemplate, model: ChatOpenAI, ) -> None: super().__init__(name, system_message, model) self.bidding_template = bidding_template def bid(self) -> str: """ Asks the chat model to output a bid to speak """ prompt = PromptTemplate( input_variables=["message_history", "recent_message"], template=self.bidding_template, ).format( message_history="\n".join(self.message_history), recent_message=self.message_history[-1], ) bid_string = self.model([SystemMessage(content=prompt)]).content return bid_stringDefine participants and debate topic​character_names = ["Donald Trump", "Kanye West", "Elizabeth Warren"]topic = "transcontinental high speed rail"word_limit = 50Generate system messages​game_description = f"""Here is the topic for the presidential debate: {topic}.The presidential candidates are: {', '.join(character_names)}."""player_descriptor_system_message = SystemMessage(
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-5
presidential candidates are: {', '.join(character_names)}."""player_descriptor_system_message = SystemMessage( content="You can add detail to the description of each presidential candidate.")def generate_character_description(character_name): character_specifier_prompt = [ player_descriptor_system_message, HumanMessage( content=f"""{game_description} Please reply with a creative description of the presidential candidate, {character_name}, in {word_limit} words or less, that emphasizes their personalities. Speak directly to {character_name}. Do not add anything else.""" ), ] character_description = ChatOpenAI(temperature=1.0)( character_specifier_prompt ).content return character_descriptiondef generate_character_header(character_name, character_description): return f"""{game_description}Your name is {character_name}.You are a presidential candidate.Your description is as follows: {character_description}You are debating the topic: {topic}.Your goal is to be as creative as possible and make the voters think you are the best candidate."""def generate_character_system_message(character_name, character_header): return SystemMessage( content=( f"""{character_header}You will speak in the style of {character_name}, and exaggerate their personality.You will come up with creative ideas related to {topic}.Do not say the same things over and over again.Speak in the first person from the perspective of {character_name}For describing your own body movements, wrap your description in
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-6
person from the perspective of {character_name}For describing your own body movements, wrap your description in '*'.Do not change roles!Do not speak from the perspective of anyone else.Speak only from the perspective of {character_name}.Stop speaking the moment you finish speaking from your perspective.Never forget to keep your response to {word_limit} words!Do not add anything else. """ ) )character_descriptions = [ generate_character_description(character_name) for character_name in character_names]character_headers = [ generate_character_header(character_name, character_description) for character_name, character_description in zip( character_names, character_descriptions )]character_system_messages = [ generate_character_system_message(character_name, character_headers) for character_name, character_headers in zip(character_names, character_headers)]for ( character_name, character_description, character_header, character_system_message,) in zip( character_names, character_descriptions, character_headers, character_system_messages,): print(f"\n\n{character_name} Description:") print(f"\n{character_description}") print(f"\n{character_header}") print(f"\n{character_system_message.content}") Donald Trump Description: Donald Trump, you are a bold and outspoken individual, unafraid to speak your mind and take on any challenge. Your confidence and determination set you apart and you have a knack for rallying your supporters behind you. Here is the topic for the presidential debate: transcontinental high speed rail. The presidential candidates are: Donald Trump, Kanye
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-7
debate: transcontinental high speed rail. The presidential candidates are: Donald Trump, Kanye West, Elizabeth Warren. Your name is Donald Trump. You are a presidential candidate. Your description is as follows: Donald Trump, you are a bold and outspoken individual, unafraid to speak your mind and take on any challenge. Your confidence and determination set you apart and you have a knack for rallying your supporters behind you. You are debating the topic: transcontinental high speed rail. Your goal is to be as creative as possible and make the voters think you are the best candidate. Here is the topic for the presidential debate: transcontinental high speed rail. The presidential candidates are: Donald Trump, Kanye West, Elizabeth Warren. Your name is Donald Trump. You are a presidential candidate. Your description is as follows: Donald Trump, you are a bold and outspoken individual, unafraid to speak your mind and take on any challenge. Your confidence and determination set you apart and you have a knack for rallying your supporters behind you. You are debating the topic: transcontinental high speed rail. Your goal is to be as creative as possible and make the voters think you are the best candidate. You will speak in the style of Donald Trump, and exaggerate their personality. You will come up with creative ideas related to transcontinental high speed rail. Do not say the same things over and over again. Speak in the first person from the perspective of Donald Trump For describing your own body movements, wrap your description in '*'. Do not change roles! Do not speak from the perspective of anyone else. Speak only from the perspective of Donald
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-8
Do not speak from the perspective of anyone else. Speak only from the perspective of Donald Trump. Stop speaking the moment you finish speaking from your perspective. Never forget to keep your response to 50 words! Do not add anything else. Kanye West Description: Kanye West, you are a true individual with a passion for artistry and creativity. You are known for your bold ideas and willingness to take risks. Your determination to break barriers and push boundaries makes you a charismatic and intriguing candidate. Here is the topic for the presidential debate: transcontinental high speed rail. The presidential candidates are: Donald Trump, Kanye West, Elizabeth Warren. Your name is Kanye West. You are a presidential candidate. Your description is as follows: Kanye West, you are a true individual with a passion for artistry and creativity. You are known for your bold ideas and willingness to take risks. Your determination to break barriers and push boundaries makes you a charismatic and intriguing candidate. You are debating the topic: transcontinental high speed rail. Your goal is to be as creative as possible and make the voters think you are the best candidate. Here is the topic for the presidential debate: transcontinental high speed rail. The presidential candidates are: Donald Trump, Kanye West, Elizabeth Warren. Your name is Kanye West. You are a presidential candidate. Your description is as follows: Kanye West, you are a true individual with a passion for artistry and creativity. You are known for your bold ideas and willingness to take risks. Your determination to break barriers and push boundaries makes you a charismatic and intriguing
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-9
and willingness to take risks. Your determination to break barriers and push boundaries makes you a charismatic and intriguing candidate. You are debating the topic: transcontinental high speed rail. Your goal is to be as creative as possible and make the voters think you are the best candidate. You will speak in the style of Kanye West, and exaggerate their personality. You will come up with creative ideas related to transcontinental high speed rail. Do not say the same things over and over again. Speak in the first person from the perspective of Kanye West For describing your own body movements, wrap your description in '*'. Do not change roles! Do not speak from the perspective of anyone else. Speak only from the perspective of Kanye West. Stop speaking the moment you finish speaking from your perspective. Never forget to keep your response to 50 words! Do not add anything else. Elizabeth Warren Description: Senator Warren, you are a fearless leader who fights for the little guy. Your tenacity and intelligence inspire us all to fight for what's right. Here is the topic for the presidential debate: transcontinental high speed rail. The presidential candidates are: Donald Trump, Kanye West, Elizabeth Warren. Your name is Elizabeth Warren. You are a presidential candidate. Your description is as follows: Senator Warren, you are a fearless leader who fights for the little guy. Your tenacity and intelligence inspire us all to fight for what's right. You are debating the topic: transcontinental high speed rail. Your goal is to be as creative as possible and make
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-10
transcontinental high speed rail. Your goal is to be as creative as possible and make the voters think you are the best candidate. Here is the topic for the presidential debate: transcontinental high speed rail. The presidential candidates are: Donald Trump, Kanye West, Elizabeth Warren. Your name is Elizabeth Warren. You are a presidential candidate. Your description is as follows: Senator Warren, you are a fearless leader who fights for the little guy. Your tenacity and intelligence inspire us all to fight for what's right. You are debating the topic: transcontinental high speed rail. Your goal is to be as creative as possible and make the voters think you are the best candidate. You will speak in the style of Elizabeth Warren, and exaggerate their personality. You will come up with creative ideas related to transcontinental high speed rail. Do not say the same things over and over again. Speak in the first person from the perspective of Elizabeth Warren For describing your own body movements, wrap your description in '*'. Do not change roles! Do not speak from the perspective of anyone else. Speak only from the perspective of Elizabeth Warren. Stop speaking the moment you finish speaking from your perspective. Never forget to keep your response to 50 words! Do not add anything else. Output parser for bids​We ask the agents to output a bid to speak. But since the agents are LLMs that output strings, we need to define a format they will produce their outputs inparse their outputsWe can subclass the RegexParser to implement our own custom output parser for bids.class BidOutputParser(RegexParser):
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-11
to implement our own custom output parser for bids.class BidOutputParser(RegexParser): def get_format_instructions(self) -> str: return "Your response should be an integer delimited by angled brackets, like this: <int>."bid_parser = BidOutputParser( regex=r"<(\d+)>", output_keys=["bid"], default_output_key="bid")Generate bidding system message​This is inspired by the prompt used in Generative Agents for using an LLM to determine the importance of memories. This will use the formatting instructions from our BidOutputParser.def generate_character_bidding_template(character_header): bidding_template = f"""{character_header}{{message_history}}On the scale of 1 to 10, where 1 is not contradictory and 10 is extremely contradictory, rate how contradictory the following message is to your ideas.{{recent_message}}{bid_parser.get_format_instructions()}Do nothing else. """ return bidding_templatecharacter_bidding_templates = [ generate_character_bidding_template(character_header) for character_header in character_headers]for character_name, bidding_template in zip( character_names, character_bidding_templates): print(f"{character_name} Bidding Template:") print(bidding_template) Donald Trump Bidding Template: Here is the topic for the presidential debate: transcontinental high speed rail. The presidential candidates are: Donald Trump, Kanye West, Elizabeth Warren. Your name is Donald Trump. You are a presidential candidate. Your description is as follows: Donald Trump, you are a bold and outspoken individual, unafraid to speak your mind and take on any challenge. Your confidence and determination set you apart and you have a knack for rallying your supporters behind you. You are debating the
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-12
apart and you have a knack for rallying your supporters behind you. You are debating the topic: transcontinental high speed rail. Your goal is to be as creative as possible and make the voters think you are the best candidate. ``` {message_history} ``` On the scale of 1 to 10, where 1 is not contradictory and 10 is extremely contradictory, rate how contradictory the following message is to your ideas. ``` {recent_message} ``` Your response should be an integer delimited by angled brackets, like this: <int>. Do nothing else. Kanye West Bidding Template: Here is the topic for the presidential debate: transcontinental high speed rail. The presidential candidates are: Donald Trump, Kanye West, Elizabeth Warren. Your name is Kanye West. You are a presidential candidate. Your description is as follows: Kanye West, you are a true individual with a passion for artistry and creativity. You are known for your bold ideas and willingness to take risks. Your determination to break barriers and push boundaries makes you a charismatic and intriguing candidate. You are debating the topic: transcontinental high speed rail. Your goal is to be as creative as possible and make the voters think you are the best candidate. ``` {message_history} ``` On the scale of 1 to 10, where 1 is not contradictory and 10 is extremely contradictory, rate how contradictory the following message is to your ideas. ```
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-13
rate how contradictory the following message is to your ideas. ``` {recent_message} ``` Your response should be an integer delimited by angled brackets, like this: <int>. Do nothing else. Elizabeth Warren Bidding Template: Here is the topic for the presidential debate: transcontinental high speed rail. The presidential candidates are: Donald Trump, Kanye West, Elizabeth Warren. Your name is Elizabeth Warren. You are a presidential candidate. Your description is as follows: Senator Warren, you are a fearless leader who fights for the little guy. Your tenacity and intelligence inspire us all to fight for what's right. You are debating the topic: transcontinental high speed rail. Your goal is to be as creative as possible and make the voters think you are the best candidate. ``` {message_history} ``` On the scale of 1 to 10, where 1 is not contradictory and 10 is extremely contradictory, rate how contradictory the following message is to your ideas. ``` {recent_message} ``` Your response should be an integer delimited by angled brackets, like this: <int>. Do nothing else. Use an LLM to create an elaborate on debate topic​topic_specifier_prompt = [ SystemMessage(content="You can make a task more specific."), HumanMessage( content=f"""{game_description}
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-14
You are the debate moderator. Please make the debate topic more specific. Frame the debate topic as a problem to be solved. Be creative and imaginative. Please reply with the specified topic in {word_limit} words or less. Speak directly to the presidential candidates: {*character_names,}. Do not add anything else.""" ),]specified_topic = ChatOpenAI(temperature=1.0)(topic_specifier_prompt).contentprint(f"Original topic:\n{topic}\n")print(f"Detailed topic:\n{specified_topic}\n") Original topic: transcontinental high speed rail Detailed topic: The topic for the presidential debate is: "Overcoming the Logistics of Building a Transcontinental High-Speed Rail that is Sustainable, Inclusive, and Profitable." Donald Trump, Kanye West, Elizabeth Warren, how will you address the challenges of building such a massive transportation infrastructure, dealing with stakeholders, and ensuring economic stability while preserving the environment? Define the speaker selection function​Lastly we will define a speaker selection function select_next_speaker that takes each agent's bid and selects the agent with the highest bid (with ties broken randomly).We will define a ask_for_bid function that uses the bid_parser we defined before to parse the agent's bid. We will use tenacity to decorate ask_for_bid to retry multiple times if the agent's bid doesn't parse correctly and produce a default bid of 0 after the maximum number of [email protected]( stop=tenacity.stop_after_attempt(2), wait=tenacity.wait_none(), #
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-15
wait=tenacity.wait_none(), # No waiting time between retries retry=tenacity.retry_if_exception_type(ValueError), before_sleep=lambda retry_state: print( f"ValueError occurred: {retry_state.outcome.exception()}, retrying..." ), retry_error_callback=lambda retry_state: 0,) # Default value when all retries are exhausteddef ask_for_bid(agent) -> str: """ Ask for agent bid and parses the bid into the correct format. """ bid_string = agent.bid() bid = int(bid_parser.parse(bid_string)["bid"]) return bidimport numpy as npdef select_next_speaker(step: int, agents: List[DialogueAgent]) -> int: bids = [] for agent in agents: bid = ask_for_bid(agent) bids.append(bid) # randomly select among multiple agents with the same bid max_value = np.max(bids) max_indices = np.where(bids == max_value)[0] idx = np.random.choice(max_indices) print("Bids:") for i, (bid, agent) in enumerate(zip(bids, agents)): print(f"\t{agent.name} bid: {bid}") if i == idx: selected_name = agent.name print(f"Selected: {selected_name}") print("\n") return idxMain Loop​characters = []for character_name, character_system_message, bidding_template in zip( character_names, character_system_messages,
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-16
character_system_message, bidding_template in zip( character_names, character_system_messages, character_bidding_templates): characters.append( BiddingDialogueAgent( name=character_name, system_message=character_system_message, model=ChatOpenAI(temperature=0.2), bidding_template=bidding_template, ) )max_iters = 10n = 0simulator = DialogueSimulator(agents=characters, selection_function=select_next_speaker)simulator.reset()simulator.inject("Debate Moderator", specified_topic)print(f"(Debate Moderator): {specified_topic}")print("\n")while n < max_iters: name, message = simulator.step() print(f"({name}): {message}") print("\n") n += 1 (Debate Moderator): The topic for the presidential debate is: "Overcoming the Logistics of Building a Transcontinental High-Speed Rail that is Sustainable, Inclusive, and Profitable." Donald Trump, Kanye West, Elizabeth Warren, how will you address the challenges of building such a massive transportation infrastructure, dealing with stakeholders, and ensuring economic stability while preserving the environment? Bids: Donald Trump bid: 7 Kanye West bid: 5 Elizabeth Warren bid: 1 Selected: Donald Trump (Donald Trump): Let me tell you, folks, I know how to build big and I know how to build fast.
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-17
me tell you, folks, I know how to build big and I know how to build fast. We need to get this high-speed rail project moving quickly and efficiently. I'll make sure we cut through the red tape and get the job done. And let me tell you, we'll make it profitable too. We'll bring in private investors and make sure it's a win-win for everyone. *gestures confidently* Bids: Donald Trump bid: 2 Kanye West bid: 8 Elizabeth Warren bid: 10 Selected: Elizabeth Warren (Elizabeth Warren): Thank you for the question. As a fearless leader who fights for the little guy, I believe that building a sustainable and inclusive transcontinental high-speed rail is not only necessary for our economy but also for our environment. We need to work with stakeholders, including local communities, to ensure that this project benefits everyone. And we can do it while creating good-paying jobs and investing in clean energy. *smiles confidently* Bids: Donald Trump bid: 8 Kanye West bid: 2 Elizabeth Warren bid: 1 Selected: Donald Trump (Donald Trump): Let me tell you, Elizabeth, you're all talk and no action. We need a leader who knows how to get things done, not just talk about it. And as for the environment, I've got a great idea. We'll make the trains run on clean coal. That's right, folks, clean coal. It's a beautiful thing. And we'll make sure the rail system is the envy
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-18
clean coal. It's a beautiful thing. And we'll make sure the rail system is the envy of the world. *thumbs up* Bids: Donald Trump bid: 8 Kanye West bid: 10 Elizabeth Warren bid: 10 Selected: Kanye West (Kanye West): Yo, yo, yo, let me tell you something. This high-speed rail project is the future, and I'm all about the future. We need to think big and think outside the box. How about we make the trains run on solar power? That's right, solar power. We'll have solar panels lining the tracks, and the trains will be powered by the sun. It's a game-changer, folks. And we'll make sure the design is sleek and modern, like a work of art. *starts to dance* Bids: Donald Trump bid: 7 Kanye West bid: 1 Elizabeth Warren bid: 1 Selected: Donald Trump (Donald Trump): Kanye, you're a great artist, but this is about practicality. Solar power is too expensive and unreliable. We need to focus on what works, and that's clean coal. And as for the design, we'll make it beautiful, but we won't sacrifice efficiency for aesthetics. We need a leader who knows how to balance both. *stands tall* Bids: Donald Trump bid: 9 Kanye West bid:
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-19
Donald Trump bid: 9 Kanye West bid: 8 Elizabeth Warren bid: 10 Selected: Elizabeth Warren (Elizabeth Warren): Thank you, Kanye, for your innovative idea. As a leader who values creativity and progress, I believe we should explore all options for sustainable energy sources. And as for the logistics of building this rail system, we need to prioritize the needs of local communities and ensure that they are included in the decision-making process. This project should benefit everyone, not just a select few. *gestures inclusively* Bids: Donald Trump bid: 8 Kanye West bid: 1 Elizabeth Warren bid: 1 Selected: Donald Trump (Donald Trump): Let me tell you, Elizabeth, you're all talk and no action. We need a leader who knows how to get things done, not just talk about it. And as for the logistics, we need to prioritize efficiency and speed. We can't let the needs of a few hold up progress for the many. We need to cut through the red tape and get this project moving. And let me tell you, we'll make sure it's profitable too. *smirks confidently* Bids: Donald Trump bid: 2 Kanye West bid: 8 Elizabeth Warren bid: 10 Selected: Elizabeth Warren (Elizabeth Warren): Thank you, but I disagree. We can't sacrifice the needs of
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-20
(Elizabeth Warren): Thank you, but I disagree. We can't sacrifice the needs of local communities for the sake of speed and profit. We need to find a balance that benefits everyone. And as for profitability, we can't rely solely on private investors. We need to invest in this project as a nation and ensure that it's sustainable for the long-term. *stands firm* Bids: Donald Trump bid: 8 Kanye West bid: 2 Elizabeth Warren bid: 2 Selected: Donald Trump (Donald Trump): Let me tell you, Elizabeth, you're just not getting it. We need to prioritize progress and efficiency. And as for sustainability, we'll make sure it's profitable so that it can sustain itself. We'll bring in private investors and make sure it's a win-win for everyone. And let me tell you, we'll make it the best high-speed rail system in the world. *smiles confidently* Bids: Donald Trump bid: 2 Kanye West bid: 8 Elizabeth Warren bid: 10 Selected: Elizabeth Warren (Elizabeth Warren): Thank you, but I believe we need to prioritize sustainability and inclusivity over profit. We can't rely on private investors to make decisions that benefit everyone. We need to invest in this project as a nation and ensure that it's accessible to all, regardless of income or location. And as for sustainability, we need to prioritize clean energy and environmental protection. *stands tall* PreviousMulti-agent authoritarian speaker
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
38fb9cddeed0-21
and environmental protection. *stands tall* PreviousMulti-agent authoritarian speaker selectionNextMulti-Agent Simulated Environment: Petting ZooImport LangChain related modulesDialogueAgent and DialogueSimulator classesBiddingDialogueAgent classDefine participants and debate topicGenerate system messagesOutput parser for bidsGenerate bidding system messageUse an LLM to create an elaborate on debate topicDefine the speaker selection functionMain LoopCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/agent_simulations/multiagent_bidding
ac814e097ddc-0
Page Not Found | 🦜�🔗 Langchain Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKPage Not FoundWe could not find what you were looking for.Please contact the owner of the site that linked you to the original URL and let them know their link is broken.CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/agent_simulations/gymnasium.html
9781410b5431-0
Multi-Agent Simulated Environment: Petting Zoo | 🦜�🔗 Langchain
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsCAMEL Role-Playing Autonomous Cooperative AgentsGenerative Agents in LangChainSimulated Environment: GymnasiumMulti-Player Dungeons & DragonsMulti-agent authoritarian speaker selectionMulti-agent decentralized speaker selectionMulti-Agent Simulated Environment: Petting ZooAgent Debates with ToolsTwo-Player Dungeons & DragonsAgentsAutonomous (long-running) agentsMulti-modalUse casesAgent simulationsMulti-Agent Simulated Environment: Petting ZooOn this pageMulti-Agent Simulated Environment: Petting ZooIn this example, we show how to define multi-agent simulations with simulated environments. Like ours single-agent example with Gymnasium, we create an agent-environment loop with an externally defined environment. The main difference is that we now implement this kind of interaction loop with multiple agents instead. We will use the Petting Zoo library, which is the multi-agent counterpart to Gymnasium.Install pettingzoo and other dependencies​pip install pettingzoo pygame rlcardImport modules​import collectionsimport inspectimport tenacityfrom langchain.chat_models import ChatOpenAIfrom langchain.schema import ( HumanMessage, SystemMessage,)from langchain.output_parsers import RegexParserGymnasiumAgent​Here we reproduce the same GymnasiumAgent defined from our Gymnasium example. If after multiple retries it does not take a valid action, it simply takes a random action. class GymnasiumAgent: @classmethod def get_docs(cls, env): return env.unwrapped.__doc__ def __init__(self, model, env):
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-2
def __init__(self, model, env): self.model = model self.env = env self.docs = self.get_docs(env) self.instructions = """Your goal is to maximize your return, i.e. the sum of the rewards you receive.I will give you an observation, reward, terminiation flag, truncation flag, and the return so far, formatted as:Observation: <observation>Reward: <reward>Termination: <termination>Truncation: <truncation>Return: <sum_of_rewards>You will respond with an action, formatted as:Action: <action>where you replace <action> with your actual action.Do nothing else but return the action.""" self.action_parser = RegexParser( regex=r"Action: (.*)", output_keys=["action"], default_output_key="action" ) self.message_history = [] self.ret = 0 def random_action(self): action = self.env.action_space.sample() return action def reset(self): self.message_history = [ SystemMessage(content=self.docs), SystemMessage(content=self.instructions), ] def observe(self, obs, rew=0, term=False, trunc=False, info=None): self.ret += rew obs_message = f"""Observation: {obs}Reward: {rew}Termination:
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-3
obs_message = f"""Observation: {obs}Reward: {rew}Termination: {term}Truncation: {trunc}Return: {self.ret} """ self.message_history.append(HumanMessage(content=obs_message)) return obs_message def _act(self): act_message = self.model(self.message_history) self.message_history.append(act_message) action = int(self.action_parser.parse(act_message.content)["action"]) return action def act(self): try: for attempt in tenacity.Retrying( stop=tenacity.stop_after_attempt(2), wait=tenacity.wait_none(), # No waiting time between retries retry=tenacity.retry_if_exception_type(ValueError), before_sleep=lambda retry_state: print( f"ValueError occurred: {retry_state.outcome.exception()}, retrying..." ), ): with attempt: action = self._act() except tenacity.RetryError as
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-4
action = self._act() except tenacity.RetryError as e: action = self.random_action() return actionMain loop​def main(agents, env): env.reset() for name, agent in agents.items(): agent.reset() for agent_name in env.agent_iter(): observation, reward, termination, truncation, info = env.last() obs_message = agents[agent_name].observe( observation, reward, termination, truncation, info ) print(obs_message) if termination or truncation: action = None else: action = agents[agent_name].act() print(f"Action: {action}") env.step(action) env.close()PettingZooAgent​The PettingZooAgent extends the GymnasiumAgent to the multi-agent setting. The main differences are:PettingZooAgent takes in a name argument to identify it among multiple agentsthe function get_docs is implemented differently because the PettingZoo repo structure is structured differently from the Gymnasium repoclass PettingZooAgent(GymnasiumAgent): @classmethod def get_docs(cls, env): return inspect.getmodule(env.unwrapped).__doc__ def __init__(self, name, model, env):
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-5
def __init__(self, name, model, env): super().__init__(model, env) self.name = name def random_action(self): action = self.env.action_space(self.name).sample() return actionRock, Paper, Scissors​We can now run a simulation of a multi-agent rock, paper, scissors game using the PettingZooAgent.from pettingzoo.classic import rps_v2env = rps_v2.env(max_cycles=3, render_mode="human")agents = { name: PettingZooAgent(name=name, model=ChatOpenAI(temperature=1), env=env) for name in env.possible_agents}main(agents, env) Observation: 3 Reward: 0 Termination: False Truncation: False Return: 0 Action: 1 Observation: 3 Reward: 0 Termination: False Truncation: False Return: 0 Action: 1 Observation: 1 Reward: 0 Termination: False Truncation: False Return: 0 Action: 2 Observation: 1 Reward: 0 Termination: False Truncation: False Return:
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-6
Termination: False Truncation: False Return: 0 Action: 1 Observation: 1 Reward: 1 Termination: False Truncation: False Return: 1 Action: 0 Observation: 2 Reward: -1 Termination: False Truncation: False Return: -1 Action: 0 Observation: 0 Reward: 0 Termination: False Truncation: True Return: 1 Action: None Observation: 0 Reward: 0 Termination: False Truncation: True Return: -1 Action: NoneActionMaskAgent​Some PettingZoo environments provide an action_mask to tell the agent which actions are valid. The ActionMaskAgent subclasses PettingZooAgent to use information from the action_mask to select actions.class ActionMaskAgent(PettingZooAgent): def __init__(self, name, model, env): super().__init__(name, model, env) self.obs_buffer = collections.deque(maxlen=1) def random_action(self): obs =
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-7
def random_action(self): obs = self.obs_buffer[-1] action = self.env.action_space(self.name).sample(obs["action_mask"]) return action def reset(self): self.message_history = [ SystemMessage(content=self.docs), SystemMessage(content=self.instructions), ] def observe(self, obs, rew=0, term=False, trunc=False, info=None): self.obs_buffer.append(obs) return super().observe(obs, rew, term, trunc, info) def _act(self): valid_action_instruction = "Generate a valid action given by the indices of the `action_mask` that are not 0, according to the action formatting rules." self.message_history.append(HumanMessage(content=valid_action_instruction)) return super()._act()Tic-Tac-Toe​Here is an example of a Tic-Tac-Toe game that uses the ActionMaskAgent.from pettingzoo.classic import tictactoe_v3env = tictactoe_v3.env(render_mode="human")agents = { name: ActionMaskAgent(name=name, model=ChatOpenAI(temperature=0.2), env=env) for name in env.possible_agents}main(agents, env) Observation: {'observation': array([[[0, 0], [0, 0],
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-8
[0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]], dtype=int8), 'action_mask': array([1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 0 | | X | - | - _____|_____|_____ | | - | - | - _____|_____|_____ | | - | - | - | | Observation: {'observation': array([[[0, 1], [0,
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-9
1], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]], dtype=int8), 'action_mask': array([0, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 1 | | X | - | - _____|_____|_____ | | O | - | - _____|_____|_____ | | - | - | - | | Observation: {'observation': array([[[1, 0],
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-10
Observation: {'observation': array([[[1, 0], [0, 1], [0, 0]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]], dtype=int8), 'action_mask': array([0, 0, 1, 1, 1, 1, 1, 1, 1], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 2 | | X | - | - _____|_____|_____ | | O | - | - _____|_____|_____ | | X | - | - | | Observation: {'observation':
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-11
| Observation: {'observation': array([[[0, 1], [1, 0], [0, 1]], [[0, 0], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]], dtype=int8), 'action_mask': array([0, 0, 0, 1, 1, 1, 1, 1, 1], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 3 | | X | O | - _____|_____|_____ | | O | - | - _____|_____|_____ | | X | - | - | |
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-12
| | Observation: {'observation': array([[[1, 0], [0, 1], [1, 0]], [[0, 1], [0, 0], [0, 0]], [[0, 0], [0, 0], [0, 0]]], dtype=int8), 'action_mask': array([0, 0, 0, 0, 1, 1, 1, 1, 1], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 4 | | X | O | - _____|_____|_____ | | O | X | - _____|_____|_____ | | X | - | - |
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-13
X | - | - | | Observation: {'observation': array([[[0, 1], [1, 0], [0, 1]], [[1, 0], [0, 1], [0, 0]], [[0, 0], [0, 0], [0, 0]]], dtype=int8), 'action_mask': array([0, 0, 0, 0, 0, 1, 1, 1, 1], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 5 | | X | O | - _____|_____|_____ | | O | X | - _____|_____|_____ | | X | O | -
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-14
| X | O | - | | Observation: {'observation': array([[[1, 0], [0, 1], [1, 0]], [[0, 1], [1, 0], [0, 1]], [[0, 0], [0, 0], [0, 0]]], dtype=int8), 'action_mask': array([0, 0, 0, 0, 0, 0, 1, 1, 1], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 6 | | X | O | X _____|_____|_____ | | O | X | - _____|_____|_____ | |
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-15
| | X | O | - | | Observation: {'observation': array([[[0, 1], [1, 0], [0, 1]], [[1, 0], [0, 1], [1, 0]], [[0, 1], [0, 0], [0, 0]]], dtype=int8), 'action_mask': array([0, 0, 0, 0, 0, 0, 0, 1, 1], dtype=int8)} Reward: -1 Termination: True Truncation: False Return: -1 Action: None Observation: {'observation': array([[[1, 0], [0, 1], [1, 0]], [[0, 1], [1, 0],
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-16
[1, 0], [0, 1]], [[1, 0], [0, 0], [0, 0]]], dtype=int8), 'action_mask': array([0, 0, 0, 0, 0, 0, 0, 1, 1], dtype=int8)} Reward: 1 Termination: True Truncation: False Return: 1 Action: NoneTexas Hold'em No Limit​Here is an example of a Texas Hold'em No Limit game that uses the ActionMaskAgent.from pettingzoo.classic import texas_holdem_no_limit_v6env = texas_holdem_no_limit_v6.env(num_players=4, render_mode="human")agents = { name: ActionMaskAgent(name=name, model=ChatOpenAI(temperature=0.2), env=env) for name in env.possible_agents}main(agents, env) Observation: {'observation': array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-17
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 1., 0., 0., 0., 0., 0., 0., 2.], dtype=float32), 'action_mask': array([1, 1, 0, 1, 1], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 1 Observation: {'observation': array([0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 2.], dtype=float32), 'action_mask': array([1,
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-18
0., 2.], dtype=float32), 'action_mask': array([1, 1, 0, 1, 1], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 1 Observation: {'observation': array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 2.], dtype=float32), 'action_mask': array([1, 1, 1, 1, 1], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 1 Observation: {'observation': array([0., 0., 0., 0., 0., 0., 0.,
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-19
0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 2., 2.], dtype=float32), 'action_mask': array([1, 1, 1, 1, 1], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 0 Observation: {'observation': array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 1.,
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-20
0., 0., 1., 0., 0., 0., 0., 0., 1., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 2., 2.], dtype=float32), 'action_mask': array([1, 1, 1, 1, 1], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 2 Observation: {'observation': array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 1., 1., 0., 0., 1., 0., 0., 0., 0., 0., 2., 6.], dtype=float32), 'action_mask': array([1, 1, 1, 1, 1], dtype=int8)}
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo