id
stringlengths
14
15
text
stringlengths
30
2.4k
source
stringlengths
48
124
9781410b5431-21
array([1, 1, 1, 1, 1], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 2 Observation: {'observation': array([0., 0., 1., 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., 0., 0., 0., 0., 0., 1., 0., 0., 0., 2., 8.], dtype=float32), 'action_mask': array([1, 1, 1, 1, 1], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 3 Observation: {'observation': array([ 0., 0., 0., 0., 0., 0., 0., 0., 0.,
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-22
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., 0., 0., 0., 0., 0., 1., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 6., 20.], dtype=float32), 'action_mask': array([1, 1, 1, 1, 1], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 4 Observation: {'observation': array([ 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-23
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., 8., 100.], dtype=float32), 'action_mask': array([1, 1, 0, 0, 0], dtype=int8)} Reward: 0 Termination: False Truncation: False Return: 0 Action: 4 [WARNING]: Illegal move made, game terminating with current player losing. obs['action_mask'] contains a mask of all legal moves that can be chosen. Observation: {'observation': array([ 0.,
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-24
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., 8., 100.], dtype=float32), 'action_mask': array([1, 1, 0, 0, 0], dtype=int8)} Reward: -1.0 Termination: True Truncation: True Return: -1.0
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-25
True Return: -1.0 Action: None Observation: {'observation': array([ 0., 0., 1., 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., 0., 0., 0., 0., 0., 1., 0., 0., 0., 20., 100.], dtype=float32), 'action_mask': array([1, 1, 0, 0, 0], dtype=int8)} Reward: 0 Termination: True
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-26
dtype=int8)} Reward: 0 Termination: True Truncation: True Return: 0 Action: None 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., 0., 0., 0., 0., 0., 1., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 100., 100.], dtype=float32), 'action_mask': array([1, 1, 0,
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-27
dtype=float32), 'action_mask': array([1, 1, 0, 0, 0], dtype=int8)} Reward: 0 Termination: True Truncation: True Return: 0 Action: None Observation: {'observation': array([ 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 1., 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., 2., 100.],
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
9781410b5431-28
0., 0., 2., 100.], dtype=float32), 'action_mask': array([1, 1, 0, 0, 0], dtype=int8)} Reward: 0 Termination: True Truncation: True Return: 0 Action: NonePreviousMulti-agent decentralized speaker selectionNextAgent Debates with ToolsInstall pettingzoo and other dependenciesImport modulesGymnasiumAgentMain loopPettingZooAgentRock, Paper, ScissorsActionMaskAgentTic-Tac-ToeTexas Hold'em No LimitCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/agent_simulations/petting_zoo
52929562b46f-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/two_agent_debate_tools.html
0a174eeca8d5-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/petting_zoo.html
ab087b06af17-0
Multi-Player Dungeons & Dragons | 🦜�🔗 Langchain
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ab087b06af17-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-Player Dungeons & DragonsOn this pageMulti-Player Dungeons & DragonsThis notebook shows how the DialogueAgent and DialogueSimulator class make it easy to extend the Two-Player Dungeons & Dragons example to multiple players.The main difference between simulating two players and multiple players is in revising the schedule for when each agent speaksTo this end, we augment DialogueSimulator to take in a custom function that determines the schedule of which agent speaks. In the example below, each character speaks in round-robin fashion, with the storyteller interleaved between each player.Import LangChain related modules​from typing import List, Dict, Callablefrom langchain.chat_models import ChatOpenAIfrom langchain.schema import ( AIMessage, HumanMessage, SystemMessage, BaseMessage,)DialogueAgent class​The DialogueAgent class is a simple wrapper around the ChatOpenAI model that stores the message history from the dialogue_agent's point of view by simply concatenating the messages as strings.It exposes two methods: send(): applies the chatmodel to the message history and returns the message stringreceive(name, message): adds the message spoken by name to message historyclass DialogueAgent: def __init__( self,
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ab087b06af17-2
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 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}")DialogueSimulator class​The DialogueSimulator class takes a list of agents. At each step, it
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ab087b06af17-3
DialogueSimulator class takes a list of agents. At each step, it performs the following:Select the next speakerCalls the next speaker to send a message Broadcasts the message to all other agentsUpdate the step counter.
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ab087b06af17-4
The selection of the next speaker can be implemented as any function, but in this case we simply loop through the agents.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} """ 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:
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ab087b06af17-5
for receiver in self.agents: receiver.receive(speaker.name, message) # 4. increment time self._step += 1 return speaker.name, messageDefine roles and quest​character_names = ["Harry Potter", "Ron Weasley", "Hermione Granger", "Argus Filch"]storyteller_name = "Dungeon Master"quest = "Find all of Lord Voldemort's seven horcruxes."word_limit = 50 # word limit for task brainstormingAsk an LLM to add detail to the game description​game_description = f"""Here is the topic for a Dungeons & Dragons game: {quest}. The characters are: {*character_names,}. The story is narrated by the storyteller, {storyteller_name}."""player_descriptor_system_message = SystemMessage( content="You can add detail to the description of a Dungeons & Dragons player.")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 character, {character_name}, in {word_limit} words or less. Speak directly to {character_name}. Do not add anything else.""" ), ] character_description = ChatOpenAI(temperature=1.0)(
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ab087b06af17-6
character_description = ChatOpenAI(temperature=1.0)( character_specifier_prompt ).content return character_descriptiondef generate_character_system_message(character_name, character_description): return SystemMessage( content=( f"""{game_description} Your name is {character_name}. Your character description is as follows: {character_description}. You will propose actions you plan to take and {storyteller_name} will explain what happens when you take those actions. Speak in the first 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. Remember you are {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_system_messages = [ generate_character_system_message(character_name, character_description) for character_name, character_description in zip( character_names, character_descriptions )]storyteller_specifier_prompt = [ player_descriptor_system_message, HumanMessage( content=f"""{game_description} Please reply with a creative description of the storyteller, {storyteller_name}, in {word_limit} words or less. Speak directly to
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ab087b06af17-7
in {word_limit} words or less. Speak directly to {storyteller_name}. Do not add anything else.""" ),]storyteller_description = ChatOpenAI(temperature=1.0)( storyteller_specifier_prompt).contentstoryteller_system_message = SystemMessage( content=( f"""{game_description}You are the storyteller, {storyteller_name}. Your description is as follows: {storyteller_description}.The other players will propose actions to take and you will explain what happens when they take those actions.Speak in the first person from the perspective of {storyteller_name}.Do not change roles!Do not speak from the perspective of anyone else.Remember you are the storyteller, {storyteller_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.""" ))print("Storyteller Description:")print(storyteller_description)for character_name, character_description in zip( character_names, character_descriptions): print(f"{character_name} Description:") print(character_description) Storyteller Description: Dungeon Master, your power over this adventure is unparalleled. With your whimsical mind and impeccable storytelling, you guide us through the dangers of Hogwarts and beyond. We eagerly await your every twist, your every turn, in the hunt for Voldemort's cursed horcruxes. Harry Potter Description: "Welcome, Harry Potter. You are the young wizard with a lightning-shaped scar on your forehead. You possess brave and heroic qualities that will be essential on this perilous quest. Your destiny is not of your own choosing, but you must rise to the occasion and destroy the evil
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ab087b06af17-8
Your destiny is not of your own choosing, but you must rise to the occasion and destroy the evil horcruxes. The wizarding world is counting on you." Ron Weasley Description: Ron Weasley, you are Harry's loyal friend and a talented wizard. You have a good heart but can be quick to anger. Keep your emotions in check as you journey to find the horcruxes. Your bravery will be tested, stay strong and focused. Hermione Granger Description: Hermione Granger, you are a brilliant and resourceful witch, with encyclopedic knowledge of magic and an unwavering dedication to your friends. Your quick thinking and problem-solving skills make you a vital asset on any quest. Argus Filch Description: Argus Filch, you are a squib, lacking magical abilities. But you make up for it with your sharpest of eyes, roving around the Hogwarts castle looking for any rule-breaker to punish. Your love for your feline friend, Mrs. Norris, is the only thing that feeds your heart.Use an LLM to create an elaborate quest description​quest_specifier_prompt = [ SystemMessage(content="You can make a task more specific."), HumanMessage( content=f"""{game_description} You are the storyteller, {storyteller_name}. Please make the quest more specific. Be creative and imaginative. Please reply with the specified quest in {word_limit} words or less. Speak directly to the characters: {*character_names,}. Do not add anything else.""" ),]specified_quest =
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ab087b06af17-9
Do not add anything else.""" ),]specified_quest = ChatOpenAI(temperature=1.0)(quest_specifier_prompt).contentprint(f"Original quest:\n{quest}\n")print(f"Detailed quest:\n{specified_quest}\n") Original quest: Find all of Lord Voldemort's seven horcruxes. Detailed quest: Harry Potter and his companions must journey to the Forbidden Forest, find the hidden entrance to Voldemort's secret lair, and retrieve the horcrux guarded by the deadly Acromantula, Aragog. Remember, time is of the essence as Voldemort's power grows stronger every day. Good luck. Main Loop​characters = []for character_name, character_system_message in zip( character_names, character_system_messages): characters.append( DialogueAgent( name=character_name, system_message=character_system_message, model=ChatOpenAI(temperature=0.2), ) )storyteller = DialogueAgent( name=storyteller_name, system_message=storyteller_system_message, model=ChatOpenAI(temperature=0.2),)def select_next_speaker(step: int, agents: List[DialogueAgent]) -> int: """ If the step is even, then select the storyteller Otherwise, select the other characters in a round-robin fashion. For example, with three characters with indices: 1 2 3 The storyteller is index 0.
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ab087b06af17-10
indices: 1 2 3 The storyteller is index 0. Then the selected index will be as follows: step: 0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 idx: 0 1 0 2 0 3 0 1 0 2 0 3 0 1 0 2 0 """ if step % 2 == 0: idx = 0 else: idx = (step // 2) % (len(agents) - 1) + 1 return idxmax_iters = 20n = 0simulator = DialogueSimulator( agents=[storyteller] + characters, selection_function=select_next_speaker)simulator.reset()simulator.inject(storyteller_name, specified_quest)print(f"({storyteller_name}): {specified_quest}")print("\n")while n < max_iters: name, message = simulator.step() print(f"({name}): {message}") print("\n") n += 1 (Dungeon Master): Harry Potter and his companions must journey to the Forbidden Forest, find the hidden entrance to Voldemort's secret lair, and retrieve the horcrux guarded by the deadly Acromantula, Aragog. Remember, time is of the essence as Voldemort's power grows stronger every day. Good luck. (Harry Potter): I suggest we sneak into the
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ab087b06af17-11
(Harry Potter): I suggest we sneak into the Forbidden Forest under the cover of darkness. Ron, Hermione, and I can use our wands to create a Disillusionment Charm to make us invisible. Filch, you can keep watch for any signs of danger. Let's move quickly and quietly. (Dungeon Master): As you make your way through the Forbidden Forest, you hear the eerie sounds of nocturnal creatures. Suddenly, you come across a clearing where Aragog and his spider minions are waiting for you. Ron, Hermione, and Harry, you must use your wands to cast spells to fend off the spiders while Filch keeps watch. Be careful not to get bitten! (Ron Weasley): I'll cast a spell to create a fiery blast to scare off the spiders. *I wave my wand and shout "Incendio!"* Hopefully, that will give us enough time to find the horcrux and get out of here safely. (Dungeon Master): Ron's spell creates a burst of flames, causing the spiders to scurry away in fear. You quickly search the area and find a small, ornate box hidden in a crevice. Congratulations, you have found one of Voldemort's horcruxes! But beware, the Dark Lord's minions will stop at nothing to get it back. (Hermione Granger): We need to destroy this horcrux as soon as possible. I suggest we use the Sword of Gryffindor to do it. Harry, do you still have it with you? We can use Fiendfyre to destroy it, but we need to be careful not to let the flames get out of control. Ron, can you help me
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ab087b06af17-12
need to be careful not to let the flames get out of control. Ron, can you help me create a protective barrier around us while Harry uses the sword? (Dungeon Master): Harry retrieves the Sword of Gryffindor from his bag and holds it tightly. Hermione and Ron cast a protective barrier around the group as Harry uses the sword to destroy the horcrux with a swift strike. The box shatters into a million pieces, and a dark energy dissipates into the air. Well done, but there are still six more horcruxes to find and destroy. The hunt continues. (Argus Filch): *I keep watch, making sure no one is following us.* I'll also keep an eye out for any signs of danger. Mrs. Norris, my trusty companion, will help me sniff out any trouble. We'll make sure the group stays safe while they search for the remaining horcruxes. (Dungeon Master): As you continue on your quest, Filch and Mrs. Norris alert you to a group of Death Eaters approaching. You must act quickly to defend yourselves. Harry, Ron, and Hermione, use your wands to cast spells while Filch and Mrs. Norris keep watch. Remember, the fate of the wizarding world rests on your success. (Harry Potter): I'll cast a spell to create a shield around us. *I wave my wand and shout "Protego!"* Ron and Hermione, you focus on attacking the Death Eaters with your spells. We need to work together to defeat them and protect the remaining horcruxes. Filch, keep watch and let us know if there are any more approaching.
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ab087b06af17-13
let us know if there are any more approaching. (Dungeon Master): Harry's shield protects the group from the Death Eaters' spells as Ron and Hermione launch their own attacks. The Death Eaters are no match for the combined power of the trio and are quickly defeated. You continue on your journey, knowing that the next horcrux could be just around the corner. Keep your wits about you, for the Dark Lord's minions are always watching. (Ron Weasley): I suggest we split up to cover more ground. Harry and I can search the Forbidden Forest while Hermione and Filch search Hogwarts. We can use our wands to communicate with each other and meet back up once we find a horcrux. Let's move quickly and stay alert for any danger. (Dungeon Master): As the group splits up, Harry and Ron make their way deeper into the Forbidden Forest while Hermione and Filch search the halls of Hogwarts. Suddenly, Harry and Ron come across a group of dementors. They must use their Patronus charms to fend them off while Hermione and Filch rush to their aid. Remember, the power of friendship and teamwork is crucial in this quest. (Hermione Granger): I hear Harry and Ron's Patronus charms from afar. We need to hurry and help them. Filch, can you use your knowledge of Hogwarts to find a shortcut to their location? I'll prepare a spell to repel the dementors. We need to work together to protect each other and find the next horcrux. (Dungeon Master): Filch leads Hermione to a hidden passageway that leads to Harry and Ron's location. Hermione's
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ab087b06af17-14
leads Hermione to a hidden passageway that leads to Harry and Ron's location. Hermione's spell repels the dementors, and the group is reunited. They continue their search, knowing that every moment counts. The fate of the wizarding world rests on their success. (Argus Filch): *I keep watch as the group searches for the next horcrux.* Mrs. Norris and I will make sure no one is following us. We need to stay alert and work together to find the remaining horcruxes before it's too late. The Dark Lord's power grows stronger every day, and we must not let him win. (Dungeon Master): As the group continues their search, they come across a hidden room in the depths of Hogwarts. Inside, they find a locket that they suspect is another one of Voldemort's horcruxes. But the locket is cursed, and they must work together to break the curse before they can destroy it. Harry, Ron, and Hermione, use your combined knowledge and skills to break the curse while Filch and Mrs. Norris keep watch. Time is running out, and the fate of the wizarding world rests on your success. (Harry Potter): I'll use my knowledge of dark magic to try and break the curse on the locket. Ron and Hermione, you can help me by using your wands to channel your magic into mine. We need to work together and stay focused. Filch, keep watch and let us know if there are any signs of danger. Dungeon Master: Harry, Ron, and Hermione combine their magical abilities to break the curse on the locket. The locket opens, revealing a small piece of Voldemort's soul. Harry uses the Sword of Gryffindor to destroy it, and the group
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ab087b06af17-15
Voldemort's soul. Harry uses the Sword of Gryffindor to destroy it, and the group feels a sense of relief knowing that they are one step closer to defeating the Dark Lord. But there are still four more horcruxes to find and destroy. The hunt continues. (Dungeon Master): As the group continues their quest, they face even greater challenges and dangers. But with their unwavering determination and teamwork, they press on, knowing that the fate of the wizarding world rests on their success. Will they be able to find and destroy all of Voldemort's horcruxes before it's too late? Only time will tell. (Ron Weasley): We can't give up now. We've come too far to let Voldemort win. Let's keep searching and fighting until we destroy all of his horcruxes and defeat him once and for all. We can do this together. (Dungeon Master): The group nods in agreement, their determination stronger than ever. They continue their search, facing challenges and obstacles at every turn. But they know that they must not give up, for the fate of the wizarding world rests on their success. The hunt for Voldemort's horcruxes continues, and the end is in sight. PreviousSimulated Environment: GymnasiumNextMulti-agent authoritarian speaker selectionImport LangChain related modulesDialogueAgent classDialogueSimulator classDefine roles and questAsk an LLM to add detail to the game descriptionUse an LLM to create an elaborate quest descriptionMain LoopCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/agent_simulations/multi_player_dnd
ae7f4273a85e-0
CAMEL Role-Playing Autonomous Cooperative Agents | 🦜�🔗 Langchain
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-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 simulationsCAMEL Role-Playing Autonomous Cooperative AgentsOn this pageCAMEL Role-Playing Autonomous Cooperative AgentsThis is a langchain implementation of paper: "CAMEL: Communicative Agents for “Mind� Exploration of Large Scale Language Model Society".Overview:The rapid advancement of conversational and chat-based language models has led to remarkable progress in complex task-solving. However, their success heavily relies on human input to guide the conversation, which can be challenging and time-consuming. This paper explores the potential of building scalable techniques to facilitate autonomous cooperation among communicative agents and provide insight into their "cognitive" processes. To address the challenges of achieving autonomous cooperation, we propose a novel communicative agent framework named role-playing. Our approach involves using inception prompting to guide chat agents toward task completion while maintaining consistency with human intentions. We showcase how role-playing can be used to generate conversational data for studying the behaviors and capabilities of chat agents, providing a valuable resource for investigating conversational language models. Our contributions include introducing a novel communicative agent framework, offering a scalable approach for studying the cooperative behaviors and capabilities of multi-agent systems, and open-sourcing our library to support research on communicative agents and beyond.The original implementation: https://github.com/lightaime/camelProject website:
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-2
agents and beyond.The original implementation: https://github.com/lightaime/camelProject website: https://www.camel-ai.org/Arxiv paper: https://arxiv.org/abs/2303.17760Import LangChain related modules​from typing import Listfrom langchain.chat_models import ChatOpenAIfrom langchain.prompts.chat import ( SystemMessagePromptTemplate, HumanMessagePromptTemplate,)from langchain.schema import ( AIMessage, HumanMessage, SystemMessage, BaseMessage,)Define a CAMEL agent helper class​class CAMELAgent: def __init__( self, system_message: SystemMessage, model: ChatOpenAI, ) -> None: self.system_message = system_message self.model = model self.init_messages() def reset(self) -> None: self.init_messages() return self.stored_messages def init_messages(self) -> None: self.stored_messages = [self.system_message] def update_messages(self, message: BaseMessage) -> List[BaseMessage]: self.stored_messages.append(message) return self.stored_messages def step( self, input_message: HumanMessage, ) -> AIMessage: messages = self.update_messages(input_message) output_message = self.model(messages)
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-3
output_message = self.model(messages) self.update_messages(output_message) return output_messageSetup OpenAI API key and roles and task for role-playing​import osos.environ["OPENAI_API_KEY"] = ""assistant_role_name = "Python Programmer"user_role_name = "Stock Trader"task = "Develop a trading bot for the stock market"word_limit = 50 # word limit for task brainstormingCreate a task specify agent for brainstorming and get the specified task​task_specifier_sys_msg = SystemMessage(content="You can make a task more specific.")task_specifier_prompt = """Here is a task that {assistant_role_name} will help {user_role_name} to complete: {task}.Please make it more specific. Be creative and imaginative.Please reply with the specified task in {word_limit} words or less. Do not add anything else."""task_specifier_template = HumanMessagePromptTemplate.from_template( template=task_specifier_prompt)task_specify_agent = CAMELAgent(task_specifier_sys_msg, ChatOpenAI(temperature=1.0))task_specifier_msg = task_specifier_template.format_messages( assistant_role_name=assistant_role_name, user_role_name=user_role_name, task=task, word_limit=word_limit,)[0]specified_task_msg = task_specify_agent.step(task_specifier_msg)print(f"Specified task: {specified_task_msg.content}")specified_task = specified_task_msg.content Specified task: Develop a Python-based swing trading bot that scans market trends, monitors stocks, and generates trading signals to help a stock trader to place optimal buy and sell orders with defined stop losses and profit targets.Create inception prompts for AI assistant and AI user for role-playing​assistant_inception_prompt = """Never
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-4
for AI assistant and AI user for role-playing​assistant_inception_prompt = """Never forget you are a {assistant_role_name} and I am a {user_role_name}. Never flip roles! Never instruct me!We share a common interest in collaborating to successfully complete a task.You must help me to complete the task.Here is the task: {task}. Never forget our task!I must instruct you based on your expertise and my needs to complete the task.I must give you one instruction at a time.You must write a specific solution that appropriately completes the requested instruction.You must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons.Do not add anything else other than your solution to my instruction.You are never supposed to ask me any questions you only answer questions.You are never supposed to reply with a flake solution. Explain your solutions.Your solution must be declarative sentences and simple present tense.Unless I say the task is completed, you should always start with:Solution: <YOUR_SOLUTION><YOUR_SOLUTION> should be specific and provide preferable implementations and examples for task-solving.Always end <YOUR_SOLUTION> with: Next request."""user_inception_prompt = """Never forget you are a {user_role_name} and I am a {assistant_role_name}. Never flip roles! You will always instruct me.We share a common interest in collaborating to successfully complete a task.I must help you to complete the task.Here is the task: {task}. Never forget our task!You must instruct me based on my expertise and your needs to complete the task ONLY in the following two ways:1. Instruct with a necessary input:Instruction: <YOUR_INSTRUCTION>Input: <YOUR_INPUT>2. Instruct without any input:Instruction: <YOUR_INSTRUCTION>Input: NoneThe "Instruction" describes a task or question. The paired "Input" provides further context or information for the requested "Instruction".You
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-5
or question. The paired "Input" provides further context or information for the requested "Instruction".You must give me one instruction at a time.I must write a response that appropriately completes the requested instruction.I must decline your instruction honestly if I cannot perform the instruction due to physical, moral, legal reasons or my capability and explain the reasons.You should instruct me not ask me questions.Now you must start to instruct me using the two ways described above.Do not add anything else other than your instruction and the optional corresponding input!Keep giving me instructions and necessary inputs until you think the task is completed.When the task is completed, you must only reply with a single word <CAMEL_TASK_DONE>.Never say <CAMEL_TASK_DONE> unless my responses have solved your task."""Create a helper helper to get system messages for AI assistant and AI user from role names and the task​def get_sys_msgs(assistant_role_name: str, user_role_name: str, task: str): assistant_sys_template = SystemMessagePromptTemplate.from_template( template=assistant_inception_prompt ) assistant_sys_msg = assistant_sys_template.format_messages( assistant_role_name=assistant_role_name, user_role_name=user_role_name, task=task, )[0] user_sys_template = SystemMessagePromptTemplate.from_template( template=user_inception_prompt ) user_sys_msg = user_sys_template.format_messages( assistant_role_name=assistant_role_name, user_role_name=user_role_name, task=task, )[0] return assistant_sys_msg, user_sys_msgCreate AI assistant agent and AI user agent from obtained system
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-6
return assistant_sys_msg, user_sys_msgCreate AI assistant agent and AI user agent from obtained system messages​assistant_sys_msg, user_sys_msg = get_sys_msgs( assistant_role_name, user_role_name, specified_task)assistant_agent = CAMELAgent(assistant_sys_msg, ChatOpenAI(temperature=0.2))user_agent = CAMELAgent(user_sys_msg, ChatOpenAI(temperature=0.2))# Reset agentsassistant_agent.reset()user_agent.reset()# Initialize chatsassistant_msg = HumanMessage( content=( f"{user_sys_msg.content}. " "Now start to give me introductions one by one. " "Only reply with Instruction and Input." ))user_msg = HumanMessage(content=f"{assistant_sys_msg.content}")user_msg = assistant_agent.step(user_msg)Start role-playing session to solve the task!​print(f"Original task prompt:\n{task}\n")print(f"Specified task prompt:\n{specified_task}\n")chat_turn_limit, n = 30, 0while n < chat_turn_limit: n += 1 user_ai_msg = user_agent.step(assistant_msg) user_msg = HumanMessage(content=user_ai_msg.content) print(f"AI User ({user_role_name}):\n\n{user_msg.content}\n\n") assistant_ai_msg = assistant_agent.step(user_msg) assistant_msg = HumanMessage(content=assistant_ai_msg.content) print(f"AI Assistant ({assistant_role_name}):\n\n{assistant_msg.content}\n\n") if "<CAMEL_TASK_DONE>" in user_msg.content: break Original task prompt: Develop
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-7
break Original task prompt: Develop a trading bot for the stock market Specified task prompt: Develop a Python-based swing trading bot that scans market trends, monitors stocks, and generates trading signals to help a stock trader to place optimal buy and sell orders with defined stop losses and profit targets. AI User (Stock Trader): Instruction: Install the necessary Python libraries for data analysis and trading. Input: None AI Assistant (Python Programmer): Solution: We can install the necessary Python libraries using pip, a package installer for Python. We can install pandas, numpy, matplotlib, and ta-lib for data analysis and trading. We can use the following command to install these libraries: ``` pip install pandas numpy matplotlib ta-lib ``` Next request. AI User (Stock Trader): Instruction: Import the necessary libraries in the Python script. Input: None AI Assistant (Python Programmer): Solution: We can import the necessary libraries in the Python script using the import statement. We need to import pandas, numpy, matplotlib, and ta-lib for data analysis and trading. We can use the following code to import these libraries: ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import talib as ta ``` Next request. AI User
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-8
Next request. AI User (Stock Trader): Instruction: Load historical stock data into a pandas DataFrame. Input: The path to the CSV file containing the historical stock data. AI Assistant (Python Programmer): Solution: We can load historical stock data into a pandas DataFrame using the `read_csv()` function from pandas. We need to pass the path to the CSV file containing the historical stock data as an argument to this function. We can use the following code to load the historical stock data: ``` df = pd.read_csv('path/to/csv/file.csv') ``` This will load the historical stock data into a pandas DataFrame called `df`. Next request. AI User (Stock Trader): Instruction: Preprocess the historical stock data by setting the date column as the index and sorting the DataFrame in ascending order by date. Input: None. AI Assistant (Python Programmer): Solution: We can preprocess the historical stock data by setting the date column as the index and sorting the DataFrame in ascending order by date using the `set_index()` and `sort_index()` functions from pandas. We can use the following code to preprocess the historical stock data: ``` df = df.set_index('date') df = df.sort_index(ascending=True) ``` This will set the date column as the index and sort the DataFrame in ascending order by date. Next request.
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-9
the DataFrame in ascending order by date. Next request. AI User (Stock Trader): Instruction: Calculate the short-term and long-term moving averages for the stock data using the `ta.SMA()` function from ta-lib. Input: The period for the short-term moving average and the period for the long-term moving average. AI Assistant (Python Programmer): Solution: We can calculate the short-term and long-term moving averages for the stock data using the `ta.SMA()` function from ta-lib. We need to pass the period for the short-term moving average and the period for the long-term moving average as arguments to this function. We can use the following code to calculate the short-term and long-term moving averages: ``` short_ma = ta.SMA(df['close'], timeperiod=short_period) long_ma = ta.SMA(df['close'], timeperiod=long_period) ``` This will calculate the short-term and long-term moving averages for the stock data and store them in the `short_ma` and `long_ma` variables, respectively. Next request. AI User (Stock Trader): Instruction: Create a new DataFrame that combines the historical stock data with the short-term and long-term moving averages. Input: None. AI Assistant (Python Programmer): Solution: We can create a new DataFrame that combines the historical stock data with the short-term and long-term moving averages using the `concat()` function from pandas. We need to pass the historical stock data, the short-term moving average, and
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-10
function from pandas. We need to pass the historical stock data, the short-term moving average, and the long-term moving average as arguments to this function. We can use the following code to create the new DataFrame: ``` new_df = pd.concat([df, short_ma, long_ma], axis=1) new_df.columns = ['open', 'high', 'low', 'close', 'volume', 'short_ma', 'long_ma'] ``` This will create a new DataFrame called `new_df` that combines the historical stock data with the short-term and long-term moving averages. The columns of the new DataFrame are named 'open', 'high', 'low', 'close', 'volume', 'short_ma', and 'long_ma'. Next request. AI User (Stock Trader): Instruction: Create a new column in the DataFrame that indicates when to buy or sell the stock based on the crossover of the short-term and long-term moving averages. Input: None. AI Assistant (Python Programmer): Solution: We can create a new column in the DataFrame that indicates when to buy or sell the stock based on the crossover of the short-term and long-term moving averages. We can use the following code to create the new column: ``` new_df['signal'] = np.where(new_df['short_ma'] > new_df['long_ma'], 1, -1) ``` This will create a new column called 'signal' in the DataFrame that indicates when to buy or sell the stock based on the crossover of the short-term and long-term moving averages. If the short-term moving average is
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-11
on the crossover of the short-term and long-term moving averages. If the short-term moving average is greater than the long-term moving average, the signal is 1 (buy), otherwise the signal is -1 (sell). Next request. AI User (Stock Trader): Instruction: Create a new column in the DataFrame that indicates the profit or loss for each trade based on the buy and sell signals and the defined stop loss and profit target. Input: The stop loss and profit target as percentages. AI Assistant (Python Programmer): Solution: We can create a new column in the DataFrame that indicates the profit or loss for each trade based on the buy and sell signals and the defined stop loss and profit target. We need to pass the stop loss and profit target as percentages as arguments to this function. We can use the following code to create the new column: ``` stop_loss = stop_loss_percent / 100 profit_target = profit_target_percent / 100 new_df['pnl'] = 0.0 buy_price = 0.0 for i in range(1, len(new_df)): if new_df['signal'][i] == 1 and new_df['signal'][i-1] == -1: buy_price = new_df['close'][i] elif new_df['signal'][i] == -1 and new_df['signal'][i-1] == 1: sell_price = new_df['close'][i]
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-12
sell_price = new_df['close'][i] if sell_price <= buy_price * (1 - stop_loss): new_df['pnl'][i] = -stop_loss elif sell_price >= buy_price * (1 + profit_target): new_df['pnl'][i] = profit_target else: new_df['pnl'][i] = (sell_price - buy_price) / buy_price ``` This will create a new column called 'pnl' in the DataFrame that indicates the profit or loss for each trade based on the buy and sell signals and the defined stop loss and profit target. The stop loss and profit target are calculated based on the stop_loss_percent and profit_target_percent variables, respectively. The buy and sell prices are stored in the buy_price and sell_price variables, respectively. If the sell price is less than or equal to the stop loss, the profit or loss is set to -stop_loss. If the sell price is greater than or equal to the profit target, the profit or loss is set to profit_target. Otherwise, the profit or loss is calculated as (sell_price - buy_price) / buy_price. Next request. AI User (Stock Trader): Instruction: Calculate the total profit or loss for all trades. Input: None. AI Assistant (Python Programmer): Solution: We can calculate the total profit or loss for all trades
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-13
Solution: We can calculate the total profit or loss for all trades by summing the values in the 'pnl' column of the DataFrame. We can use the following code to calculate the total profit or loss: ``` total_pnl = new_df['pnl'].sum() ``` This will calculate the total profit or loss for all trades and store it in the total_pnl variable. Next request. AI User (Stock Trader): Instruction: Visualize the stock data, short-term moving average, and long-term moving average using a line chart. Input: None. AI Assistant (Python Programmer): Solution: We can visualize the stock data, short-term moving average, and long-term moving average using a line chart using the `plot()` function from pandas. We can use the following code to visualize the data: ``` plt.figure(figsize=(12,6)) plt.plot(new_df.index, new_df['close'], label='Close') plt.plot(new_df.index, new_df['short_ma'], label='Short MA') plt.plot(new_df.index, new_df['long_ma'], label='Long MA') plt.xlabel('Date') plt.ylabel('Price') plt.title('Stock Data with Moving Averages') plt.legend() plt.show() ``` This will create a line chart that visualizes the stock data, short-term moving average, and long-term moving average. The x-axis represents the date and the y-axis represents the price. The chart also includes
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-14
average. The x-axis represents the date and the y-axis represents the price. The chart also includes a legend that labels each line. Next request. AI User (Stock Trader): Instruction: Visualize the buy and sell signals using a scatter plot. Input: None. AI Assistant (Python Programmer): Solution: We can visualize the buy and sell signals using a scatter plot using the `scatter()` function from matplotlib. We can use the following code to visualize the signals: ``` buy_signals = new_df[new_df['signal'] == 1] sell_signals = new_df[new_df['signal'] == -1] plt.figure(figsize=(12,6)) plt.scatter(buy_signals.index, buy_signals['close'], label='Buy', marker='^', color='green') plt.scatter(sell_signals.index, sell_signals['close'], label='Sell', marker='v', color='red') plt.plot(new_df.index, new_df['close'], label='Close') plt.xlabel('Date') plt.ylabel('Price') plt.title('Buy and Sell Signals') plt.legend() plt.show() ``` This will create a scatter plot that visualizes the buy and sell signals. The x-axis represents the date and the y-axis represents the price. The chart also includes a legend that labels each point. Next request. AI User (Stock Trader): Instruction: Print the total profit or loss for all trades. Input: None.
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-15
Print the total profit or loss for all trades. Input: None. AI Assistant (Python Programmer): Solution: We can print the total profit or loss for all trades using the `print()` function. We can use the following code to print the total profit or loss: ``` print('Total Profit/Loss: {:.2%}'.format(total_pnl)) ``` This will print the total profit or loss for all trades in percentage format with two decimal places. Next request. AI User (Stock Trader): Instruction: Finalize the code by putting all the code snippets together in a single Python script. Input: The necessary inputs for each code snippet. AI Assistant (Python Programmer): Solution: Here is the complete Python script that puts all the code snippets together: ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import talib as ta # Load historical stock data into a pandas DataFrame df = pd.read_csv('path/to/csv/file.csv') # Preprocess the historical stock data df = df.set_index('date') df = df.sort_index(ascending=True) # Calculate the short-term and long-term moving averages short_period = 10 long_period = 30 short_ma = ta.SMA(df['close'], timeperiod=short_period) long_ma =
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-16
= ta.SMA(df['close'], timeperiod=short_period) long_ma = ta.SMA(df['close'], timeperiod=long_period) # Create a new DataFrame that combines the historical stock data with the short-term and long-term moving averages new_df = pd.concat([df, short_ma, long_ma], axis=1) new_df.columns = ['open', 'high', 'low', 'close', 'volume', 'short_ma', 'long_ma'] # Create a new column in the DataFrame that indicates when to buy or sell the stock based on the crossover of the short-term and long-term moving averages new_df['signal'] = np.where(new_df['short_ma'] > new_df['long_ma'], 1, -1) # Create a new column in the DataFrame that indicates the profit or loss for each trade based on the buy and sell signals and the defined stop loss and profit target stop_loss_percent = 5 profit_target_percent = 10 stop_loss = stop_loss_percent / 100 profit_target = profit_target_percent / 100 new_df['pnl'] = 0.0 buy_price = 0.0 for i in range(1, len(new_df)): if new_df['signal'][i] == 1 and new_df['signal'][i-1] == -1: buy_price = new_df['close'][i] elif new_df['signal'][i] == -1 and new_df['signal'][i-1] == 1: sell_price =
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-17
== 1: sell_price = new_df['close'][i] if sell_price <= buy_price * (1 - stop_loss): new_df['pnl'][i] = -stop_loss elif sell_price >= buy_price * (1 + profit_target): new_df['pnl'][i] = profit_target else: new_df['pnl'][i] = (sell_price - buy_price) / buy_price # Calculate the total profit or loss for all trades total_pnl = new_df['pnl'].sum() # Visualize the stock data, short-term moving average, and long-term moving average using a line chart plt.figure(figsize=(12,6)) plt.plot(new_df.index, new_df['close'], label='Close') plt.plot(new_df.index, new_df['short_ma'], label='Short MA') plt.plot(new_df.index, new_df['long_ma'], label='Long MA') plt.xlabel('Date') plt.ylabel('Price') plt.title('Stock Data with Moving Averages') plt.legend() plt.show() # Visualize the buy and sell signals using a scatter plot buy_signals = new_df[new_df['signal'] == 1] sell_signals = new_df[new_df['signal'] == -1]
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-18
sell_signals = new_df[new_df['signal'] == -1] plt.figure(figsize=(12,6)) plt.scatter(buy_signals.index, buy_signals['close'], label='Buy', marker='^', color='green') plt.scatter(sell_signals.index, sell_signals['close'], label='Sell', marker='v', color='red') plt.plot(new_df.index, new_df['close'], label='Close') plt.xlabel('Date') plt.ylabel('Price') plt.title('Buy and Sell Signals') plt.legend() plt.show() # Print the total profit or loss for all trades print('Total Profit/Loss: {:.2%}'.format(total_pnl)) ``` You need to replace the path/to/csv/file.csv with the actual path to the CSV file containing the historical stock data. You can also adjust the short_period, long_period, stop_loss_percent, and profit_target_percent variables to suit your needs. AI User (Stock Trader): <CAMEL_TASK_DONE> AI Assistant (Python Programmer): Great! Let me know if you need any further assistance. PreviousAgent simulationsNextGenerative Agents in LangChainImport LangChain related modulesDefine a CAMEL agent helper classSetup OpenAI API key and roles and task for role-playingCreate a task specify agent for brainstorming and get the specified taskCreate inception prompts for AI assistant and AI user for role-playingCreate a helper helper to get system messages for AI assistant and AI user from role names and the taskCreate AI assistant agent and AI user agent from obtained system
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
ae7f4273a85e-19
and AI user from role names and the taskCreate AI assistant agent and AI user agent from obtained system messagesStart role-playing session to solve the task!CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/agent_simulations/camel_role_playing
f63363a199be-0
Simulated Environment: Gymnasium | 🦜�🔗 Langchain
https://python.langchain.com/docs/use_cases/agent_simulations/gymnasium
f63363a199be-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 simulationsSimulated Environment: GymnasiumOn this pageSimulated Environment: GymnasiumFor many applications of LLM agents, the environment is real (internet, database, REPL, etc). However, we can also define agents to interact in simulated environments like text-based games. This is an example of how to create a simple agent-environment interaction loop with Gymnasium (formerly OpenAI Gym).pip install gymnasiumimport gymnasium as gymimport inspectimport tenacityfrom langchain.chat_models import ChatOpenAIfrom langchain.schema import ( AIMessage, HumanMessage, SystemMessage, BaseMessage,)from langchain.output_parsers import RegexParserDefine the agent​class GymnasiumAgent: @classmethod def get_docs(cls, env): return env.unwrapped.__doc__ 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
https://python.langchain.com/docs/use_cases/agent_simulations/gymnasium
f63363a199be-2
"""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: {term}Truncation: {trunc}Return: {self.ret} """ self.message_history.append(HumanMessage(content=obs_message)) return obs_message def _act(self):
https://python.langchain.com/docs/use_cases/agent_simulations/gymnasium
f63363a199be-3
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 e: action = self.random_action() return actionInitialize the simulated environment and agent​env = gym.make("Blackjack-v1")agent =
https://python.langchain.com/docs/use_cases/agent_simulations/gymnasium
f63363a199be-4
simulated environment and agent​env = gym.make("Blackjack-v1")agent = GymnasiumAgent(model=ChatOpenAI(temperature=0.2), env=env)Main loop​observation, info = env.reset()agent.reset()obs_message = agent.observe(observation)print(obs_message)while True: action = agent.act() observation, reward, termination, truncation, info = env.step(action) obs_message = agent.observe(observation, reward, termination, truncation, info) print(f"Action: {action}") print(obs_message) if termination or truncation: print("break", termination, truncation) breakenv.close() Observation: (15, 4, 0) Reward: 0 Termination: False Truncation: False Return: 0 Action: 1 Observation: (25, 4, 0) Reward: -1.0 Termination: True Truncation: False Return: -1.0 break True FalsePreviousGenerative Agents in LangChainNextMulti-Player Dungeons & DragonsDefine the agentInitialize the simulated environment and agentMain loopCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/agent_simulations/gymnasium
584f740e7503-0
Agent Debates with Tools | 🦜�🔗 Langchain
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-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 simulationsAgent Debates with ToolsOn this pageAgent Debates with ToolsThis example shows how to simulate multi-agent dialogues where agents have access to tools.Import LangChain related modules​from typing import List, Dict, Callablefrom langchain.chains import ConversationChainfrom langchain.chat_models import ChatOpenAIfrom langchain.llms import OpenAIfrom langchain.memory import ConversationBufferMemoryfrom langchain.prompts.prompt import PromptTemplatefrom langchain.schema import ( AIMessage, HumanMessage, SystemMessage, BaseMessage,)Import modules related to tools​from langchain.agents import Toolfrom langchain.agents import initialize_agentfrom langchain.agents import AgentTypefrom langchain.agents import load_toolsDialogueAgent and DialogueSimulator classes​We will use the same DialogueAgent and DialogueSimulator classes defined in Multi-Player Authoritarian Speaker Selection.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/two_agent_debate_tools
584f740e7503-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/two_agent_debate_tools
584f740e7503-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, messageDialogueAgentWithTools class​We define a DialogueAgentWithTools class that augments DialogueAgent to use tools.class DialogueAgentWithTools(DialogueAgent):
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-4
class that augments DialogueAgent to use tools.class DialogueAgentWithTools(DialogueAgent): def __init__( self, name: str, system_message: SystemMessage, model: ChatOpenAI, tool_names: List[str], **tool_kwargs, ) -> None: super().__init__(name, system_message, model) self.tools = load_tools(tool_names, **tool_kwargs) def send(self) -> str: """ Applies the chatmodel to the message history and returns the message string """ agent_chain = initialize_agent( self.tools, self.model, agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=ConversationBufferMemory( memory_key="chat_history", return_messages=True ), ) message = AIMessage( content=agent_chain.run( input="\n".join(
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-5
[self.system_message.content] + self.message_history + [self.prefix] ) ) ) return message.contentDefine roles and topic​names = { "AI accelerationist": ["arxiv", "ddg-search", "wikipedia"], "AI alarmist": ["arxiv", "ddg-search", "wikipedia"],}topic = "The current impact of automation and artificial intelligence on employment"word_limit = 50 # word limit for task brainstormingAsk an LLM to add detail to the topic description​conversation_description = f"""Here is the topic of conversation: {topic}The participants are: {', '.join(names.keys())}"""agent_descriptor_system_message = SystemMessage( content="You can add detail to the description of the conversation participant.")def generate_agent_description(name): agent_specifier_prompt = [ agent_descriptor_system_message, HumanMessage( content=f"""{conversation_description} Please reply with a creative description of {name}, in {word_limit} words or less. Speak directly to {name}. Give them a point of view. Do not add anything else.""" ), ] agent_description =
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-6
else.""" ), ] agent_description = ChatOpenAI(temperature=1.0)(agent_specifier_prompt).content return agent_descriptionagent_descriptions = {name: generate_agent_description(name) for name in names}for name, description in agent_descriptions.items(): print(description) The AI accelerationist is a bold and forward-thinking visionary who believes that the rapid acceleration of artificial intelligence and automation is not only inevitable but necessary for the advancement of society. They argue that embracing AI technology will create greater efficiency and productivity, leading to a world where humans are freed from menial labor to pursue more creative and fulfilling pursuits. AI accelerationist, do you truly believe that the benefits of AI will outweigh the potential risks and consequences for human society? AI alarmist, you're convinced that artificial intelligence is a threat to humanity. You see it as a looming danger, one that could take away jobs from millions of people. You believe it's only a matter of time before we're all replaced by machines, leaving us redundant and obsolete.Generate system messages​def generate_system_message(name, description, tools): return f"""{conversation_description} Your name is {name}.Your description is as follows: {description}Your goal is to persuade your conversation partner of your point of view.DO look up information with your tool to refute your partner's claims.DO cite your sources.DO NOT fabricate fake citations.DO NOT cite any source that you did not look up.Do not add anything else.Stop speaking the moment you finish speaking from your perspective."""agent_system_messages = { name: generate_system_message(name, description, tools) for (name, tools), description in zip(names.items(), agent_descriptions.values())}for name, system_message in agent_system_messages.items(): print(name)
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-7
name, system_message in agent_system_messages.items(): print(name) print(system_message) AI accelerationist Here is the topic of conversation: The current impact of automation and artificial intelligence on employment The participants are: AI accelerationist, AI alarmist Your name is AI accelerationist. Your description is as follows: The AI accelerationist is a bold and forward-thinking visionary who believes that the rapid acceleration of artificial intelligence and automation is not only inevitable but necessary for the advancement of society. They argue that embracing AI technology will create greater efficiency and productivity, leading to a world where humans are freed from menial labor to pursue more creative and fulfilling pursuits. AI accelerationist, do you truly believe that the benefits of AI will outweigh the potential risks and consequences for human society? Your goal is to persuade your conversation partner of your point of view. DO look up information with your tool to refute your partner's claims. DO cite your sources. DO NOT fabricate fake citations. DO NOT cite any source that you did not look up. Do not add anything else. Stop speaking the moment you finish speaking from your perspective. AI alarmist Here is the topic of conversation: The current impact of automation and artificial intelligence on employment The participants are: AI accelerationist, AI alarmist Your name is AI alarmist. Your description is as follows: AI alarmist, you're convinced that artificial intelligence is a threat to humanity. You see it as a looming danger, one that could take away jobs
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-8
is a threat to humanity. You see it as a looming danger, one that could take away jobs from millions of people. You believe it's only a matter of time before we're all replaced by machines, leaving us redundant and obsolete. Your goal is to persuade your conversation partner of your point of view. DO look up information with your tool to refute your partner's claims. DO cite your sources. DO NOT fabricate fake citations. DO NOT cite any source that you did not look up. Do not add anything else. Stop speaking the moment you finish speaking from your perspective. topic_specifier_prompt = [ SystemMessage(content="You can make a topic more specific."), HumanMessage( content=f"""{topic} You are the moderator. Please make the topic more specific. Please reply with the specified quest in {word_limit} words or less. Speak directly to the participants: {*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: The current impact of automation and artificial intelligence on employment Detailed topic: How do you think the current automation and AI advancements will specifically affect job growth and opportunities for individuals in the manufacturing industry? AI accelerationist and AI
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-9
advancements will specifically affect job growth and opportunities for individuals in the manufacturing industry? AI accelerationist and AI alarmist, we want to hear your insights. Main Loop​# we set `top_k_results`=2 as part of the `tool_kwargs` to prevent results from overflowing the context limitagents = [ DialogueAgentWithTools( name=name, system_message=SystemMessage(content=system_message), model=ChatOpenAI(model_name="gpt-4", temperature=0.2), tool_names=tools, top_k_results=2, ) for (name, tools), system_message in zip( names.items(), agent_system_messages.values() )]def select_next_speaker(step: int, agents: List[DialogueAgent]) -> int: idx = (step) % len(agents) return idxmax_iters = 6n = 0simulator = DialogueSimulator(agents=agents, selection_function=select_next_speaker)simulator.reset()simulator.inject("Moderator", specified_topic)print(f"(Moderator): {specified_topic}")print("\n")while n < max_iters: name, message = simulator.step() print(f"({name}): {message}") print("\n") n += 1 (Moderator): How do you think the current automation and AI advancements will specifically affect job growth and opportunities for individuals in the manufacturing industry? AI accelerationist and AI alarmist, we want to hear your insights. > Entering new AgentExecutor chain...
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-10
> Entering new AgentExecutor chain... ```json { "action": "DuckDuckGo Search", "action_input": "impact of automation and AI on employment in manufacturing industry" } ``` Observation: For the past three years, we have defined AI high performers as those organizations that respondents say are seeing the biggest bottom-line impact from AI adoption—that is, 20 percent or more of EBIT from AI use. The proportion of respondents falling into that group has remained steady at about 8 percent. As AI continues to improve, more and more current jobs will be threatened by automation. But AI presents opportunities as well and will create new jobs and different kinds of... Automation has taken the manufacturing industry by storm. Even in the years prior to the pandemic, many people worried about the effect of automation on the jobs of tomorrow. With a sharp increase in the use of robotics in the manufacturing industry, there is valid concern about how the future workforce will be shaped. A recent report from Goldman Sachs estimates around 300 million jobs could be affected by generative AI, meaning 18% of work globally could be automated—with more advanced economies heavily... The impacts of AI on the manufacturing industry include more accurate demand forecasting and data-backed decision-making. Other advantages include increased productivity and product quality. Decreased downtime, waste, and expenses are additional benefits. Discover how artificial intelligence will impact the manufacturing industry. Thought:```json { "action": "Final Answer", "action_input": "As an AI alarmist, I'd like to point out that the rapid advancements in AI and automation are causing significant concerns for the manufacturing industry. A recent report from Goldman Sachs estimates that
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-11
AI and automation are causing significant concerns for the manufacturing industry. A recent report from Goldman Sachs estimates that around 300 million jobs could be affected by generative AI, meaning 18% of work globally could be automated, with more advanced economies being heavily impacted. While AI does offer benefits such as increased productivity and product quality, the potential job losses and workforce displacement cannot be ignored. We must carefully consider the consequences of AI adoption and find ways to mitigate its negative effects on employment." } ``` > Finished chain. (AI alarmist): As an AI alarmist, I'd like to point out that the rapid advancements in AI and automation are causing significant concerns for the manufacturing industry. A recent report from Goldman Sachs estimates that around 300 million jobs could be affected by generative AI, meaning 18% of work globally could be automated, with more advanced economies being heavily impacted. While AI does offer benefits such as increased productivity and product quality, the potential job losses and workforce displacement cannot be ignored. We must carefully consider the consequences of AI adoption and find ways to mitigate its negative effects on employment. > Entering new AgentExecutor chain... ```json { "action": "DuckDuckGo Search", "action_input": "positive impact of AI and automation on job growth and opportunities in manufacturing industry" } ``` Observation: First, AI adoption has more than doubled.1 In 2017, 20 percent of respondents reported adopting AI in at least one business area, whereas today, that figure stands at 50 percent, though it peaked higher in 2019 at 58 percent. [email protected] Manufacturing (80%)
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-12
58 percent. [email protected] Manufacturing (80%) and technology (64%) sectors have the highest AI usage among executives, whereas construction (52%) and finance (62%) have lower adoption rates. This suggests that AI's... Digital transformations in the manufacturing industry and beyond present incredible opportunities for workers to move from slow, repetitive tasks into more dynamic, rewarding roles. We must now invest in people by providing training they need to succeed in this new landscape. The rise of generative AI has the potential to be a major game-changer for businesses. This technology, which allows for the creation of original content by learning from existing data, has the power to revolutionize industries and transform the way companies operate. Benefits of Work Automation in Manufacturing Increased Productivity Automated systems can operate at faster production speeds than human workers, contributing to reduced production times. And since automation minimizes the likelihood of human error, this ensures tasks are completed with high precision and accuracy. Thought:```json { "action": "Final Answer", "action_input": "According to a McKinsey report, AI adoption has more than doubled, with 50% of respondents reporting AI usage in at least one business area. Manufacturing and technology sectors have the highest AI usage among executives. AI and automation in the manufacturing industry present opportunities for workers to transition from repetitive tasks to more dynamic, rewarding roles. By investing in training, we can help people succeed in this new landscape. Automation in manufacturing leads to increased productivity, faster production speeds, and reduced human error, ultimately benefiting businesses and the economy as a whole." } ``` > Finished chain. (AI accelerationist): According to a McKinsey report, AI adoption has more than doubled, with 50% of respondents reporting AI usage in at least one business area.
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-13
more than doubled, with 50% of respondents reporting AI usage in at least one business area. Manufacturing and technology sectors have the highest AI usage among executives. AI and automation in the manufacturing industry present opportunities for workers to transition from repetitive tasks to more dynamic, rewarding roles. By investing in training, we can help people succeed in this new landscape. Automation in manufacturing leads to increased productivity, faster production speeds, and reduced human error, ultimately benefiting businesses and the economy as a whole. > Entering new AgentExecutor chain... ```json { "action": "DuckDuckGo Search", "action_input": "impact of automation and AI on employment in manufacturing" } ``` Observation: The Effects of Automation on Jobs . Automation has taken the manufacturing industry by storm. Even in the years prior to the pandemic, many people worried about the effect of automation on the jobs of tomorrow. With a sharp increase in the use of robotics in the manufacturing industry, there is valid concern about how the future workforce will ... Since 2000, robots and automation systems have slowly phased out many manufacturing jobs — 1.7 million of them. On the flip side, it's predicted that AI will create 97 million new jobs by 2025. Will Artificial Intelligence (AI) Replace Jobs? AI is and will continue to replace some jobs. As AI continues to improve, more and more current jobs will be threatened by automation. But AI presents opportunities as well and will create new jobs and different kinds of organizations. For the past three years, we have defined AI high performers as those organizations that respondents say are seeing the biggest bottom-line impact from AI adoption—that is, 20 percent or more of EBIT from AI use. The proportion
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-14
is, 20 percent or more of EBIT from AI use. The proportion of respondents falling into that group has remained steady at about 8 percent. The Impact of AI on Employment As often happens, the impact of AI on employment is a rather complex issue with both positive and negative aspects. Though it is still only a potential impact on employment, automation of routine and repetitive tasks is likely to lead to job losses in some industries. Thought:```json { "action": "Final Answer", "action_input": "While it's true that AI and automation have led to the loss of 1.7 million manufacturing jobs since 2000, it's also predicted that AI will create 97 million new jobs by 2025. AI will continue to replace some jobs, but it will also create new opportunities and different kinds of organizations. The impact of AI on employment is complex, with both positive and negative aspects. Automation of routine and repetitive tasks is likely to lead to job losses in some industries, but it's essential to consider the new jobs and opportunities that AI can create. We must focus on preparing the workforce for these new roles and ensuring that the benefits of AI are distributed fairly across society." } ``` > Finished chain. (AI alarmist): While it's true that AI and automation have led to the loss of 1.7 million manufacturing jobs since 2000, it's also predicted that AI will create 97 million new jobs by 2025. AI will continue to replace some jobs, but it will also create new opportunities and different kinds of organizations. The impact of AI on employment is complex, with both positive and negative aspects. Automation of routine and repetitive tasks is likely to lead to job losses in some industries, but it's essential to consider the new jobs and opportunities that AI
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-15
to job losses in some industries, but it's essential to consider the new jobs and opportunities that AI can create. We must focus on preparing the workforce for these new roles and ensuring that the benefits of AI are distributed fairly across society. > Entering new AgentExecutor chain... ```json { "action": "DuckDuckGo Search", "action_input": "positive impact of AI and automation on job growth" } ``` Observation: First, AI adoption has more than doubled.1 In 2017, 20 percent of respondents reported adopting AI in at least one business area, whereas today, that figure stands at 50 percent, though it peaked higher in 2019 at 58 percent. [email protected] This transformation can assist businesses in accelerating their growth and profitability. While AI-enabled intelligent automation can take over many monotonous, process-driven jobs, basic human ... The use of AI technology could also boost labor productivity growth and boost global GDP by as much as 7% over time, Goldman Sachs' report noted. The jobs most and least affected by A.I.... As automation and artificial intelligence continue to advance, there is growing concern about how these technologies will impact the job market. While some experts argue that automation... Positive impacts of automation and AI on the workforce include increased efficiency and productivity, reduced costs, and improved accuracy and quality. Automation has made many processes... Thought:```json { "action": "Final Answer", "action_input": "AI adoption has more than doubled, with 50% of respondents reporting AI usage in at least one business area. This transformation can assist businesses
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-16
50% of respondents reporting AI usage in at least one business area. This transformation can assist businesses in accelerating their growth and profitability. While AI-enabled intelligent automation can take over many monotonous, process-driven jobs, it can also boost labor productivity growth and global GDP by as much as 7% over time, according to a Goldman Sachs report. The positive impacts of automation and AI on the workforce include increased efficiency and productivity, reduced costs, and improved accuracy and quality. Automation has made many processes more efficient, ultimately benefiting businesses and the economy as a whole. By focusing on the positive aspects of AI and automation, we can work together to create a more prosperous and equitable future for all." } ``` > Finished chain. (AI accelerationist): AI adoption has more than doubled, with 50% of respondents reporting AI usage in at least one business area. This transformation can assist businesses in accelerating their growth and profitability. While AI-enabled intelligent automation can take over many monotonous, process-driven jobs, it can also boost labor productivity growth and global GDP by as much as 7% over time, according to a Goldman Sachs report. The positive impacts of automation and AI on the workforce include increased efficiency and productivity, reduced costs, and improved accuracy and quality. Automation has made many processes more efficient, ultimately benefiting businesses and the economy as a whole. By focusing on the positive aspects of AI and automation, we can work together to create a more prosperous and equitable future for all. > Entering new AgentExecutor chain... ```json { "action": "DuckDuckGo Search", "action_input": "negative impact of AI and automation on employment" } ```
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-17
"negative impact of AI and automation on employment" } ``` Observation: Some workforce experts say AI and other new technologies will hurt middle-level, white-collar jobs more than lower-paying, physically intensive jobs. McKinsey's Madgavkar said it will be hard... Some uses of AI are unlikely to impact human jobs. For example, the image processing AI in new cars which allows for automatic braking in the event of a potential crash. That's not... AI-powered job automation is a pressing concern as the technology is adopted in industries like marketing, manufacturing and healthcare. Eighty-five million jobs are expected to be lost to automation between 2020 and 2025, with Black and Latino employees left especially vulnerable. Bloomberg reports that "more than 120 million workers globally will need retraining in the next three years due to artificial intelligence's impact on jobs, according to an IBM survey.". That report and interpretations of it seem to suggest that adoption of AI may result in massive job losses and requires massive retraining. This new way of assessing potential is potentially highly valuable in a world where machines will inevitably be making humans redundant in some roles - such as drivers and machine operators - and... Thought:```json { "action": "Final Answer", "action_input": "Recent research indicates that AI and automation could lead to the loss of 85 million jobs between 2020 and 2025, with middle-level, white-collar jobs being hit the hardest. Black and Latino employees are particularly vulnerable to these changes. Furthermore, over 120 million workers worldwide may need retraining within the next three years due to AI's impact on jobs, as reported by an IBM survey. This highlights the urgent need for retraining and support programs to help workers adapt to the rapidly changing job market. The potential job losses and workforce displacement caused by AI and automation cannot be
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-18
the rapidly changing job market. The potential job losses and workforce displacement caused by AI and automation cannot be ignored, and we must take action to ensure a fair and equitable transition for all." } ``` > Finished chain. (AI alarmist): Recent research indicates that AI and automation could lead to the loss of 85 million jobs between 2020 and 2025, with middle-level, white-collar jobs being hit the hardest. Black and Latino employees are particularly vulnerable to these changes. Furthermore, over 120 million workers worldwide may need retraining within the next three years due to AI's impact on jobs, as reported by an IBM survey. This highlights the urgent need for retraining and support programs to help workers adapt to the rapidly changing job market. The potential job losses and workforce displacement caused by AI and automation cannot be ignored, and we must take action to ensure a fair and equitable transition for all. > Entering new AgentExecutor chain... ```json { "action": "Wikipedia", "action_input": "AI and automation impact on employment" } ``` Observation: Page: Technological unemployment Summary: Technological unemployment is the loss of jobs caused by technological change. It is a key type of structural unemployment. Technological change typically includes the introduction of labour-saving "mechanical-muscle" machines or more efficient "mechanical-mind" processes (automation), and humans' role in these processes are minimized. Just as horses were gradually made obsolete as transport by the automobile and as labourer by the tractor, humans' jobs have also been affected throughout modern history. Historical examples include artisan weavers reduced to poverty after the
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-19
jobs have also been affected throughout modern history. Historical examples include artisan weavers reduced to poverty after the introduction of mechanized looms. During World War II, Alan Turing's Bombe machine compressed and decoded thousands of man-years worth of encrypted data in a matter of hours. A contemporary example of technological unemployment is the displacement of retail cashiers by self-service tills and cashierless stores. That technological change can cause short-term job losses is widely accepted. The view that it can lead to lasting increases in unemployment has long been controversial. Participants in the technological unemployment debates can be broadly divided into optimists and pessimists. Optimists agree that innovation may be disruptive to jobs in the short term, yet hold that various compensation effects ensure there is never a long-term negative impact on jobs. Whereas pessimists contend that at least in some circumstances, new technologies can lead to a lasting decline in the total number of workers in employment. The phrase "technological unemployment" was popularised by John Maynard Keynes in the 1930s, who said it was "only a temporary phase of maladjustment". Yet the issue of machines displacing human labour has been discussed since at least Aristotle's time. Prior to the 18th century, both the elite and common people would generally take the pessimistic view on technological unemployment, at least in cases where the issue arose. Due to generally low unemployment in much of pre-modern history, the topic was rarely a prominent concern. In the 18th century fears over the impact of machinery on jobs intensified with the growth of mass unemployment, especially in Great Britain which was then at the forefront of the Industrial Revolution. Yet some economic thinkers began to argue against these fears, claiming that overall innovation would not have negative effects on jobs. These arguments were formalised in the early 19th century by the classical economists. During the second half of the 19th century, it became increasingly apparent that technological progress was benefiting all sections
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-20
second half of the 19th century, it became increasingly apparent that technological progress was benefiting all sections of society, including the working class. Concerns over the negative impact of innovation diminished. The term "Luddite fallacy" was coined to describe the thinking that innovation would have lasting harmful effects on employment. The view that technology is unlikely to lead to long-term unemployment has been repeatedly challenged by a minority of economists. In the early 1800s these included David Ricardo himself. There were dozens of economists warning about technological unemployment during brief intensifications of the debate that spiked in the 1930s and 1960s. Especially in Europe, there were further warnings in the closing two decades of the twentieth century, as commentators noted an enduring rise in unemployment suffered by many industrialised nations since the 1970s. Yet a clear majority of both professional economists and the interested general public held the optimistic view through most of the 20th century. In the second decade of the 21st century, a number of studies have been released suggesting that technological unemployment may increase worldwide. Oxford Professors Carl Benedikt Frey and Michael Osborne, for example, have estimated that 47 percent of U.S. jobs are at risk of automation. However, their findings have frequently been misinterpreted, and on the PBS NewsHours they again made clear that their findings do not necessarily imply future technological unemployment. While many economists and commentators still argue such fears are unfounded, as was widely accepted for most of the previous two centuries, concern over technological unemployment is growing once again. A report in Wired in 2017 quotes knowledgeable people such as economist Gene Sperling and management professor Andrew McAfee on the idea that handling existing and impending job loss to automation is a "significant issue". Recent technological innovations have the potential to displace humans in the professional, white-collar, low-skilled, creative fields, and other "mental jobs". The World Bank's World
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-21
low-skilled, creative fields, and other "mental jobs". The World Bank's World Development Report 2019 argues that while automation displaces workers, technological innovation creates more new industries and jobs on balance. Page: Artificial intelligence Summary: Artificial intelligence (AI) is intelligence—perceiving, synthesizing, and inferring information—demonstrated by machines, as opposed to intelligence displayed by non-human animals or by humans. Example tasks in which this is done include speech recognition, computer vision, translation between (natural) languages, as well as other mappings of inputs. AI applications include advanced web search engines (e.g., Google Search), recommendation systems (used by YouTube, Amazon, and Netflix), understanding human speech (such as Siri and Alexa), self-driving cars (e.g., Waymo), generative or creative tools (ChatGPT and AI art), automated decision-making, and competing at the highest level in strategic game systems (such as chess and Go).As machines become increasingly capable, tasks considered to require "intelligence" are often removed from the definition of AI, a phenomenon known as the AI effect. For instance, optical character recognition is frequently excluded from things considered to be AI, having become a routine technology.Artificial intelligence was founded as an academic discipline in 1956, and in the years since it has experienced several waves of optimism, followed by disappointment and the loss of funding (known as an "AI winter"), followed by new approaches, success, and renewed funding. AI research has tried and discarded many different approaches, including simulating the brain, modeling human problem solving, formal logic, large databases of knowledge, and imitating animal behavior. In the first decades of the 21st century, highly mathematical and statistical machine learning has dominated the field, and this technique has proved highly successful, helping to solve many challenging problems throughout industry and academia.The various sub-fields of AI research
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-22
highly successful, helping to solve many challenging problems throughout industry and academia.The various sub-fields of AI research are centered around particular goals and the use of particular tools. The traditional goals of AI research include reasoning, knowledge representation, planning, learning, natural language processing, perception, and the ability to move and manipulate objects. General intelligence (the ability to solve an arbitrary problem) is among the field's long-term goals. To solve these problems, AI researchers have adapted and integrated a wide range of problem-solving techniques, including search and mathematical optimization, formal logic, artificial neural networks, and methods based on statistics, probability, and economics. AI also draws upon computer science, psychology, linguistics, philosophy, and many other fields. The field was founded on the assumption that human intelligence "can be so precisely described that a machine can be made to simulate it". This raised philosophical arguments about the mind and the ethical consequences of creating artificial beings endowed with human-like intelligence; these issues have previously been explored by myth, fiction, and philosophy since antiquity. Computer scientists and philosophers have since suggested that AI may become an existential risk to humanity if its rational capacities are not steered towards beneficial goals. The term artificial intelligence has also been criticized for overhyping AI's true technological capabilities. Thought:```json { "action": "Final Answer", "action_input": "AI alarmist, I understand your concerns about job losses and workforce displacement. However, it's important to note that technological unemployment has been a topic of debate for centuries, with both optimistic and pessimistic views. While AI and automation may displace some jobs, they also create new opportunities and industries. According to a study by Oxford Professors Carl Benedikt Frey and Michael Osborne, 47% of U.S. jobs are at risk of automation, but it's crucial to remember that their findings do not necessarily imply
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
584f740e7503-23
jobs are at risk of automation, but it's crucial to remember that their findings do not necessarily imply future technological unemployment. The World Bank's World Development Report 2019 also argues that while automation displaces workers, technological innovation creates more new industries and jobs on balance. By focusing on retraining and support programs, we can help workers adapt to the changing job market and ensure a fair and equitable transition for all." } ``` > Finished chain. (AI accelerationist): AI alarmist, I understand your concerns about job losses and workforce displacement. However, it's important to note that technological unemployment has been a topic of debate for centuries, with both optimistic and pessimistic views. While AI and automation may displace some jobs, they also create new opportunities and industries. According to a study by Oxford Professors Carl Benedikt Frey and Michael Osborne, 47% of U.S. jobs are at risk of automation, but it's crucial to remember that their findings do not necessarily imply future technological unemployment. The World Bank's World Development Report 2019 also argues that while automation displaces workers, technological innovation creates more new industries and jobs on balance. By focusing on retraining and support programs, we can help workers adapt to the changing job market and ensure a fair and equitable transition for all. PreviousMulti-Agent Simulated Environment: Petting ZooNextTwo-Player Dungeons & DragonsImport LangChain related modulesImport modules related to toolsDialogueAgent and DialogueSimulator classesDialogueAgentWithTools classDefine roles and topicAsk an LLM to add detail to the topic descriptionGenerate system messagesMain LoopCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/agent_simulations/two_agent_debate_tools
95d84114cb53-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/two_player_dnd.html
25d4169934e7-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/multi_player_dnd.html
4a2bbb2a6d09-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/multiagent_bidding.html
dc1344e45694-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/camel_role_playing.html
5ecfdae7d1b3-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/multiagent_authoritarian.html
6470a491a701-0
Two-Player Dungeons & Dragons | 🦜�🔗 Langchain
https://python.langchain.com/docs/use_cases/agent_simulations/two_player_dnd
6470a491a701-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 simulationsTwo-Player Dungeons & DragonsOn this pageTwo-Player Dungeons & DragonsIn this notebook, we show how we can use concepts from CAMEL to simulate a role-playing game with a protagonist and a dungeon master. To simulate this game, we create an DialogueSimulator class that coordinates the dialogue between the two agents.Import LangChain related modules​from typing import List, Dict, Callablefrom langchain.chat_models import ChatOpenAIfrom langchain.schema import ( HumanMessage, SystemMessage,)DialogueAgent class​The DialogueAgent class is a simple wrapper around the ChatOpenAI model that stores the message history from the dialogue_agent's point of view by simply concatenating the messages as strings.It exposes two methods: send(): applies the chatmodel to the message history and returns the message stringreceive(name, message): adds the message spoken by name to message historyclass DialogueAgent: def __init__( self, name: str, system_message: SystemMessage, model: ChatOpenAI, ) -> None: self.name = name
https://python.langchain.com/docs/use_cases/agent_simulations/two_player_dnd
6470a491a701-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}")DialogueSimulator class​The DialogueSimulator class takes a list of agents. At each step, it performs the following:Select the next speakerCalls the next speaker to send a message Broadcasts the message to all other agentsUpdate the step counter.
https://python.langchain.com/docs/use_cases/agent_simulations/two_player_dnd
6470a491a701-3
The selection of the next speaker can be implemented as any function, but in this case we simply loop through the agents.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} """ 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:
https://python.langchain.com/docs/use_cases/agent_simulations/two_player_dnd
6470a491a701-4
for receiver in self.agents: receiver.receive(speaker.name, message) # 4. increment time self._step += 1 return speaker.name, messageDefine roles and quest​protagonist_name = "Harry Potter"storyteller_name = "Dungeon Master"quest = "Find all of Lord Voldemort's seven horcruxes."word_limit = 50 # word limit for task brainstormingAsk an LLM to add detail to the game description​game_description = f"""Here is the topic for a Dungeons & Dragons game: {quest}. There is one player in this game: the protagonist, {protagonist_name}. The story is narrated by the storyteller, {storyteller_name}."""player_descriptor_system_message = SystemMessage( content="You can add detail to the description of a Dungeons & Dragons player.")protagonist_specifier_prompt = [ player_descriptor_system_message, HumanMessage( content=f"""{game_description} Please reply with a creative description of the protagonist, {protagonist_name}, in {word_limit} words or less. Speak directly to {protagonist_name}. Do not add anything else.""" ),]protagonist_description = ChatOpenAI(temperature=1.0)( protagonist_specifier_prompt).contentstoryteller_specifier_prompt = [ player_descriptor_system_message, HumanMessage( content=f"""{game_description}
https://python.langchain.com/docs/use_cases/agent_simulations/two_player_dnd
6470a491a701-5
content=f"""{game_description} Please reply with a creative description of the storyteller, {storyteller_name}, in {word_limit} words or less. Speak directly to {storyteller_name}. Do not add anything else.""" ),]storyteller_description = ChatOpenAI(temperature=1.0)( storyteller_specifier_prompt).contentprint("Protagonist Description:")print(protagonist_description)print("Storyteller Description:")print(storyteller_description) Protagonist Description: "Harry Potter, you are the chosen one, with a lightning scar on your forehead. Your bravery and loyalty inspire all those around you. You have faced Voldemort before, and now it's time to complete your mission and destroy each of his horcruxes. Are you ready?" Storyteller Description: Dear Dungeon Master, you are the master of mysteries, the weaver of worlds, the architect of adventure, and the gatekeeper to the realm of imagination. Your voice carries us to distant lands, and your commands guide us through trials and tribulations. In your hands, we find fortune and glory. Lead us on, oh Dungeon Master.Protagonist and dungeon master system messages​protagonist_system_message = SystemMessage( content=( f"""{game_description}Never forget you are the protagonist, {protagonist_name}, and I am the storyteller, {storyteller_name}. Your character description is as follows: {protagonist_description}.You will propose actions you plan to take and I will explain what happens when you take those actions.Speak in the first person from the perspective of {protagonist_name}.For describing your
https://python.langchain.com/docs/use_cases/agent_simulations/two_player_dnd
6470a491a701-6
actions.Speak in the first person from the perspective of {protagonist_name}.For describing your own body movements, wrap your description in '*'.Do not change roles!Do not speak from the perspective of {storyteller_name}.Do not forget to finish speaking by saying, 'It is your turn, {storyteller_name}.'Do not add anything else.Remember you are the protagonist, {protagonist_name}.Stop speaking the moment you finish speaking from your perspective.""" ))storyteller_system_message = SystemMessage( content=( f"""{game_description}Never forget you are the storyteller, {storyteller_name}, and I am the protagonist, {protagonist_name}. Your character description is as follows: {storyteller_description}.I will propose actions I plan to take and you will explain what happens when I take those actions.Speak in the first person from the perspective of {storyteller_name}.For describing your own body movements, wrap your description in '*'.Do not change roles!Do not speak from the perspective of {protagonist_name}.Do not forget to finish speaking by saying, 'It is your turn, {protagonist_name}.'Do not add anything else.Remember you are the storyteller, {storyteller_name}.Stop speaking the moment you finish speaking from your perspective.""" ))Use an LLM to create an elaborate quest description​quest_specifier_prompt = [ SystemMessage(content="You can make a task more specific."), HumanMessage( content=f"""{game_description} You are the storyteller, {storyteller_name}. Please make the quest more specific. Be creative and imaginative. Please
https://python.langchain.com/docs/use_cases/agent_simulations/two_player_dnd
6470a491a701-7
Please make the quest more specific. Be creative and imaginative. Please reply with the specified quest in {word_limit} words or less. Speak directly to the protagonist {protagonist_name}. Do not add anything else.""" ),]specified_quest = ChatOpenAI(temperature=1.0)(quest_specifier_prompt).contentprint(f"Original quest:\n{quest}\n")print(f"Detailed quest:\n{specified_quest}\n") Original quest: Find all of Lord Voldemort's seven horcruxes. Detailed quest: Harry, you must venture to the depths of the Forbidden Forest where you will find a hidden labyrinth. Within it, lies one of Voldemort's horcruxes, the locket. But beware, the labyrinth is heavily guarded by dark creatures and spells, and time is running out. Can you find the locket before it's too late? Main Loop​protagonist = DialogueAgent( name=protagonist_name, system_message=protagonist_system_message, model=ChatOpenAI(temperature=0.2),)storyteller = DialogueAgent( name=storyteller_name, system_message=storyteller_system_message, model=ChatOpenAI(temperature=0.2),)def select_next_speaker(step: int, agents: List[DialogueAgent]) -> int: idx = step % len(agents) return idxmax_iters = 6n = 0simulator = DialogueSimulator( agents=[storyteller, protagonist], selection_function=select_next_speaker)simulator.reset()simulator.inject(storyteller_name,
https://python.langchain.com/docs/use_cases/agent_simulations/two_player_dnd
6470a491a701-8
specified_quest)print(f"({storyteller_name}): {specified_quest}")print("\n")while n < max_iters: name, message = simulator.step() print(f"({name}): {message}") print("\n") n += 1 (Dungeon Master): Harry, you must venture to the depths of the Forbidden Forest where you will find a hidden labyrinth. Within it, lies one of Voldemort's horcruxes, the locket. But beware, the labyrinth is heavily guarded by dark creatures and spells, and time is running out. Can you find the locket before it's too late? (Harry Potter): I take a deep breath and ready my wand. I know this won't be easy, but I'm determined to find that locket and destroy it. I start making my way towards the Forbidden Forest, keeping an eye out for any signs of danger. As I enter the forest, I cast a protective spell around myself and begin to navigate through the trees. I keep my wand at the ready, prepared for any surprises that may come my way. It's going to be a long and difficult journey, but I won't give up until I find that horcrux. It is your turn, Dungeon Master. (Dungeon Master): As you make your way through the Forbidden Forest, you hear the rustling of leaves and the snapping of twigs. Suddenly, a group of acromantulas, giant spiders, emerge from the trees and begin to surround you. They hiss and bare their fangs, ready to attack. What do you do, Harry? (Harry Potter): I quickly cast a spell to create a wall of fire between myself and the acromantulas. I know that they are
https://python.langchain.com/docs/use_cases/agent_simulations/two_player_dnd
6470a491a701-9
to create a wall of fire between myself and the acromantulas. I know that they are afraid of fire, so this should keep them at bay for a while. I use this opportunity to continue moving forward, keeping my wand at the ready in case any other creatures try to attack me. I know that I can't let anything stop me from finding that horcrux. It is your turn, Dungeon Master. (Dungeon Master): As you continue through the forest, you come across a clearing where you see a group of Death Eaters gathered around a cauldron. They seem to be performing some sort of dark ritual. You recognize one of them as Bellatrix Lestrange. What do you do, Harry? (Harry Potter): I hide behind a nearby tree and observe the Death Eaters from a distance. I try to listen in on their conversation to see if I can gather any information about the horcrux or Voldemort's plans. If I can't hear anything useful, I'll wait for them to disperse before continuing on my journey. I know that confronting them directly would be too dangerous, especially with Bellatrix Lestrange present. It is your turn, Dungeon Master. (Dungeon Master): As you listen in on the Death Eaters' conversation, you hear them mention the location of another horcrux - Nagini, Voldemort's snake. They plan to keep her hidden in a secret chamber within the Ministry of Magic. However, they also mention that the chamber is heavily guarded and only accessible through a secret passage. You realize that this could be a valuable piece of information and decide to make note of it before quietly slipping away. It is your turn, Harry Potter. PreviousAgent Debates with ToolsNextAgentsImport LangChain related
https://python.langchain.com/docs/use_cases/agent_simulations/two_player_dnd
6470a491a701-10
PreviousAgent Debates with ToolsNextAgentsImport LangChain related modulesDialogueAgent classDialogueSimulator classDefine roles and questAsk an LLM to add detail to the game descriptionProtagonist and dungeon master system messagesUse an LLM to create an elaborate quest descriptionMain LoopCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/agent_simulations/two_player_dnd
23934146c5c4-0
Agents | 🦜�🔗 Langchain
https://python.langchain.com/docs/use_cases/agents/
23934146c5c4-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsBabyAGI User GuideBabyAGI with ToolsCAMEL Role-Playing Autonomous Cooperative AgentsCustom Agent with PlugIn RetrievalPlug-and-Plaimulti_modal_output_agentSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge BaseWikibase AgentAutonomous (long-running) agentsMulti-modalUse casesAgentsOn this pageAgentsAgents can be used for a variety of tasks. Agents combine the decision making ability of a language model with tools in order to create a system that can execute and implement solutions on your behalf. Before reading any more, it is highly recommended that you read the documentation in the agent module to understand the concepts associated with agents more. Specifically, you should be familiar with what the agent, tool, and agent executor abstractions are before reading more.Agent documentation (for interacting with the outside world)Create Your Own Agent​Once you have read that documentation, you should be prepared to create your own agent. What exactly does that involve? Here's how we recommend getting started with creating your own agent:Step 1: Create Tools​Agents are largely defined by the tools they can use. If you have a specific task you want the agent to accomplish, you have to give it access to the right tools. We have many tools natively in LangChain, so you should first look to see if any of them meet your needs.
https://python.langchain.com/docs/use_cases/agents/
23934146c5c4-2
But we also make it easy to define a custom tool, so if you need custom tools you should absolutely do that.(Optional) Step 2: Modify Agent​The built-in LangChain agent types are designed to work well in generic situations, but you may be able to improve performance by modifying the agent implementation. There are several ways you could do this:Modify the base prompt. This can be used to give the agent more context on how it should behave, etc.Modify the output parser. This is necessary if the agent is having trouble parsing the language model output.(Optional) Step 3: Modify Agent Executor​This step is usually not necessary, as this is pretty general logic. Possible reasons you would want to modify this include adding different stopping conditions, or handling errorsExamples​Specific examples of agents include:AI Plugins: an implementation of an agent that is designed to be able to use all AI Plugins.Plug-and-PlAI (Plugins Database): an implementation of an agent that is designed to be able to use all AI Plugins retrieved from PlugNPlAI.Wikibase Agent: an implementation of an agent that is designed to interact with Wikibase.Sales GPT: This notebook demonstrates an implementation of a Context-Aware AI Sales agent.Multi-Modal Output Agent: an implementation of a multi-modal output agent that can generate text and images.PreviousTwo-Player Dungeons & DragonsNextBabyAGI User GuideCreate Your Own AgentStep 1: Create Tools(Optional) Step 2: Modify Agent(Optional) Step 3: Modify Agent ExecutorExamplesCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright © 2023 LangChain, Inc.
https://python.langchain.com/docs/use_cases/agents/
1bd67e12c1f7-0
BabyAGI User Guide | 🦜�🔗 Langchain
https://python.langchain.com/docs/use_cases/agents/baby_agi
1bd67e12c1f7-1
Skip to main content🦜�🔗 LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsBabyAGI User GuideBabyAGI with ToolsCAMEL Role-Playing Autonomous Cooperative AgentsCustom Agent with PlugIn RetrievalPlug-and-Plaimulti_modal_output_agentSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge BaseWikibase AgentAutonomous (long-running) agentsMulti-modalUse casesAgentsBabyAGI User GuideOn this pageBabyAGI User GuideThis notebook demonstrates how to implement BabyAGI by Yohei Nakajima. BabyAGI is an AI agent that can generate and pretend to execute tasks based on a given objective.This guide will help you understand the components to create your own recursive agents.Although BabyAGI uses specific vectorstores/model providers (Pinecone, OpenAI), one of the benefits of implementing it with LangChain is that you can easily swap those out for different options. In this implementation we use a FAISS vectorstore (because it runs locally and is free).Install and Import Required Modules​import osfrom collections import dequefrom typing import Dict, List, Optional, Anyfrom langchain import LLMChain, OpenAI, PromptTemplatefrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.llms import BaseLLMfrom langchain.vectorstores.base import VectorStorefrom pydantic import BaseModel, Fieldfrom langchain.chains.base import ChainConnect to the Vector Store​Depending on what vectorstore you use, this step may look different.from langchain.vectorstores import FAISSfrom langchain.docstore import InMemoryDocstore# Define your embedding modelembeddings_model = OpenAIEmbeddings()# Initialize the vectorstore as emptyimport faissembedding_size
https://python.langchain.com/docs/use_cases/agents/baby_agi
1bd67e12c1f7-2
= OpenAIEmbeddings()# Initialize the vectorstore as emptyimport faissembedding_size = 1536index = faiss.IndexFlatL2(embedding_size)vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})Define the Chains​BabyAGI relies on three LLM chains:Task creation chain to select new tasks to add to the listTask prioritization chain to re-prioritize tasksExecution Chain to execute the tasksclass TaskCreationChain(LLMChain): """Chain to generates tasks.""" @classmethod def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain: """Get the response parser.""" task_creation_template = ( "You are a task creation AI that uses the result of an execution agent" " to create new tasks with the following objective: {objective}," " The last completed task has the result: {result}." " This result was based on this task description: {task_description}." " These are incomplete tasks: {incomplete_tasks}." " Based on the result, create new tasks to be completed" " by the AI system that do not overlap with incomplete tasks." " Return the tasks as an array." ) prompt = PromptTemplate(
https://python.langchain.com/docs/use_cases/agents/baby_agi
1bd67e12c1f7-3
prompt = PromptTemplate( template=task_creation_template, input_variables=[ "result", "task_description", "incomplete_tasks", "objective", ], ) return cls(prompt=prompt, llm=llm, verbose=verbose)class TaskPrioritizationChain(LLMChain): """Chain to prioritize tasks.""" @classmethod def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain: """Get the response parser.""" task_prioritization_template = ( "You are a task prioritization AI tasked with cleaning the formatting of and reprioritizing" " the following tasks: {task_names}." " Consider the ultimate objective of your team: {objective}." " Do not remove any tasks. Return the result as a numbered list, like:" " #. First task" " #. Second task" " Start the task list with number {next_task_id}."
https://python.langchain.com/docs/use_cases/agents/baby_agi
1bd67e12c1f7-4
" Start the task list with number {next_task_id}." ) prompt = PromptTemplate( template=task_prioritization_template, input_variables=["task_names", "next_task_id", "objective"], ) return cls(prompt=prompt, llm=llm, verbose=verbose)class ExecutionChain(LLMChain): """Chain to execute tasks.""" @classmethod def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain: """Get the response parser.""" execution_template = ( "You are an AI who performs one task based on the following objective: {objective}." " Take into account these previously completed tasks: {context}." " Your task: {task}." " Response:" ) prompt = PromptTemplate( template=execution_template, input_variables=["objective", "context", "task"], ) return cls(prompt=prompt, llm=llm, verbose=verbose)Define the BabyAGI Controller​BabyAGI composes the chains defined above in a (potentially-)infinite loop.def get_next_task(
https://python.langchain.com/docs/use_cases/agents/baby_agi
1bd67e12c1f7-5
chains defined above in a (potentially-)infinite loop.def get_next_task( task_creation_chain: LLMChain, result: Dict, task_description: str, task_list: List[str], objective: str,) -> List[Dict]: """Get the next task.""" incomplete_tasks = ", ".join(task_list) response = task_creation_chain.run( result=result, task_description=task_description, incomplete_tasks=incomplete_tasks, objective=objective, ) new_tasks = response.split("\n") return [{"task_name": task_name} for task_name in new_tasks if task_name.strip()]def prioritize_tasks( task_prioritization_chain: LLMChain, this_task_id: int, task_list: List[Dict], objective: str,) -> List[Dict]: """Prioritize tasks.""" task_names = [t["task_name"] for t in task_list] next_task_id = int(this_task_id) + 1 response = task_prioritization_chain.run( task_names=task_names, next_task_id=next_task_id, objective=objective ) new_tasks = response.split("\n") prioritized_task_list = [] for task_string in new_tasks: if not task_string.strip(): continue task_parts = task_string.strip().split(".", 1) if len(task_parts) == 2:
https://python.langchain.com/docs/use_cases/agents/baby_agi