id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
e68868dde1c5-16 | 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'... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
e68868dde1c5-17 | Truncation: 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., ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
e68868dde1c5-18 | 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... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
e68868dde1c5-19 | 0., 0., 0., 0., 0., 0., 1., 0., 0., 1., 0.,
0., 0., 0., 0., 0., 0., 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: None
Contents
Install pettingzoo and ot... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1603c4ad07ab-0 | .ipynb
.pdf
Multi-Player Dungeons & Dragons
Contents
Import LangChain related modules
DialogueAgent class
DialogueSimulator class
Define roles and quest
Ask an LLM to add detail to the game description
Use an LLM to create an elaborate quest description
Main Loop
Multi-Player Dungeons & Dragons#
This notebook shows h... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
1603c4ad07ab-1 | 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.s... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
1603c4ad07ab-2 | 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
mes... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
1603c4ad07ab-3 | Do not add anything else."""
)
]
character_description = ChatOpenAI(temperature=1.0)(character_specifier_prompt).content
return character_description
def generate_character_system_message(character_name, character_description):
return SystemMessage(content=(
f"""{game_description}
Yo... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
1603c4ad07ab-4 | storyteller_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 fr... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
1603c4ad07ab-5 | 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... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
1603c4ad07ab-6 | 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=sto... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
1603c4ad07ab-7 | 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 Pott... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
1603c4ad07ab-8 | (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.
(Hermi... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
1603c4ad07ab-9 | (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 approachi... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
1603c4ad07ab-10 | (Dungeon Master): Filch 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 th... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
1603c4ad07ab-11 | 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 feels a sense of relief knowing that they are one step closer to defeating the Dark Lo... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
8b50f8ffb1e5-0 | .ipynb
.pdf
CAMEL Role-Playing Autonomous Cooperative Agents
Contents
Import LangChain related modules
Define a CAMEL agent helper class
Setup OpenAI API key and roles and task for role-playing
Create a task specify agent for brainstorming and get the specified task
Create inception prompts for AI assistant and AI us... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
8b50f8ffb1e5-1 | Arxiv paper: https://arxiv.org/abs/2303.17760
Import LangChain related modules#
from typing import List
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
SystemMessagePromptTemplate,
HumanMessagePromptTemplate,
)
from langchain.schema import (
AIMessage,
HumanMessage,
... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
8b50f8ffb1e5-2 | Create 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 ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
8b50f8ffb1e5-3 | 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 ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
8b50f8ffb1e5-4 | 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... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
8b50f8ffb1e5-5 | "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"Specifie... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
8b50f8ffb1e5-6 | 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, ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
8b50f8ffb1e5-7 | 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.
AI User (Stock Trader):
Instruction: Calculate the short-term and long-term moving averages for the stock data using the `ta.SMA()` function from t... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
8b50f8ffb1e5-8 | ```
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 ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
8b50f8ffb1e5-9 | 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 a... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
8b50f8ffb1e5-10 | ```
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.... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
8b50f8ffb1e5-11 | 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 tha... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
8b50f8ffb1e5-12 | AI User (Stock Trader):
Instruction: 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: {... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
8b50f8ffb1e5-13 | # 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 ba... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
8b50f8ffb1e5-14 | 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 ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
8b50f8ffb1e5-15 | Create a task specify agent for brainstorming and get the specified task
Create inception prompts for AI assistant and AI user for role-playing
Create a helper helper to get system messages for AI assistant and AI user from role names and the task
Create AI assistant agent and AI user agent from obtained system message... | https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
5cf0ea5faac4-0 | .ipynb
.pdf
Multi-agent authoritarian speaker selection
Contents
Import LangChain related modules
DialogueAgent and DialogueSimulator classes
DirectorDialogueAgent class
Define participants and topic
Generate system messages
Use an LLM to create an elaborate on debate topic
Define the speaker selection function
Main ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-1 | 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.s... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-2 | # 3. everyone receives message
for receiver in self.agents:
receiver.receive(speaker.name, message)
# 4. increment time
self._step += 1
return speaker.name, message
DirectorDialogueAgent class#
The DirectorDialogueAgent is a privileged agent that chooses which of the other ag... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-3 | class IntegerOutputParser(RegexParser):
def get_format_instructions(self) -> str:
return 'Your response should be an integer delimited by angled brackets, like this: <int>.'
class DirectorDialogueAgent(DialogueAgent):
def __init__(
self,
name,
system_message: SystemMessage,
... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-4 | {self.choice_parser.get_format_instructions()}
Do nothing else.
""")
# 3. have a prompt for prompting the next speaker to speak
self.prompt_next_speaker_prompt_template = PromptTemplate(
input_variables=["message_history", "next_speaker"],
template=f"""{{message_... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-5 | choice_prompt = self.choose_next_speaker_prompt_template.format(
message_history='\n'.join(self.message_history + [self.prefix] + [self.response]),
speaker_names=speaker_names
)
choice_string = self.model(
[
self.system_message,
HumanMe... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-6 | director_name = "Jon Stewart"
agent_summaries = OrderedDict({
"Jon Stewart": ("Host of the Daily Show", "New York"),
"Samantha Bee": ("Hollywood Correspondent", "Los Angeles"),
"Aasif Mandvi": ("CIA Correspondent", "Washington D.C."),
"Ronny Chieng": ("Average American Correspondent", "Cleveland, Ohio"... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-7 | Your description is as follows: {agent_description}
You are discussing the topic: {topic}.
Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location.
"""
def generate_agent_system_message(agent_name, agent_header):
return SystemMe... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-8 | print(f'\nSystem Message:\n{system_message.content}')
Jon Stewart Description:
Jon Stewart, the sharp-tongued and quick-witted host of the Daily Show, holding it down in the hustle and bustle of New York City. Ready to deliver the news with a comedic twist, while keeping it real in the city that never sleeps.
Header:
T... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-9 | - Aasif Mandvi: CIA Correspondent, located in Washington D.C.
- Ronny Chieng: Average American Correspondent, located in Cleveland, Ohio.
Your name is Jon Stewart, your role is Host of the Daily Show, and you are located in New York.
Your description is as follows: Jon Stewart, the sharp-tongued and quick-witted host o... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-10 | The episode features
- Jon Stewart: Host of the Daily Show, located in New York
- Samantha Bee: Hollywood Correspondent, located in Los Angeles
- Aasif Mandvi: CIA Correspondent, located in Washington D.C.
- Ronny Chieng: Average American Correspondent, located in Cleveland, Ohio.
Your name is Samantha Bee, your role ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-11 | You are discussing the topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze.
Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location.
You will speak in the style of Samantha Bee, and exagger... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-12 | Your description is as follows: Aasif Mandvi, the CIA Correspondent in the heart of Washington D.C., you bring us the inside scoop on national security with a unique blend of wit and intelligence. The nation's capital is lucky to have you, Aasif - keep those secrets safe!
You are discussing the topic: The New Workout T... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-13 | Do not say the same things over and over again.
Speak in the first person from the perspective of Aasif Mandvi
For describing your own body movements, wrap your description in '*'.
Do not change roles!
Do not speak from the perspective of anyone else.
Speak only from the perspective of Aasif Mandvi.
Stop speaking the m... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-14 | Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location.
System Message:
This is a Daily Show episode discussing the following topic: The New Workout Trend: Competitive Sitting - How Laziness Became the Next Fitness Craze.
The episo... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-15 | Never forget to keep your response to 50 words!
Do not add anything else.
Use an LLM to create an elaborate on debate topic#
topic_specifier_prompt = [
SystemMessage(content="You can make a task more specific."),
HumanMessage(content=
f"""{conversation_description}
Please elaborate... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-16 | """
# the director speaks on odd steps
if step % 2 == 1:
idx = 0
else:
# here the director chooses the next speaker
idx = director.select_next_speaker() + 1 # +1 because we excluded the director
return idx
Main Loop#
director = DirectorDialogueAgent(
name=director_name, ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-17 | Stop? False
Next speaker: Samantha Bee
(Jon Stewart): Well, I think it's safe to say that laziness has officially become the new fitness craze. I mean, who needs to break a sweat when you can just sit your way to victory? But in all seriousness, I think people are drawn to the idea of competition and the sense of acco... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-18 | (Ronny Chieng): Well, Jon, I gotta say, I'm not surprised that competitive sitting is taking off. I mean, have you seen the size of the chairs these days? They're practically begging us to sit in them all day. And as for exercise routines, let's just say I've never been one for the gym. But I can definitely see the app... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-19 | (Aasif Mandvi): Well Jon, as a CIA correspondent, I have to say that I'm always thinking about the potential threats to our nation's security. And while competitive sitting may seem harmless, there could be some unforeseen consequences. For example, what if our enemies start training their soldiers in the art of sittin... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-20 | (Ronny Chieng): Absolutely, Jon. We live in a world where everything is at our fingertips, and we expect things to be easy and convenient. So it's no surprise that people are drawn to a fitness trend that requires minimal effort and can be done from the comfort of their own homes. But I think it's important to remember... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
5cf0ea5faac4-21 | (Samantha Bee): Oh, Jon, you know I love a good conspiracy theory. And let me tell you, I think there's something more sinister at play here. I mean, think about it - what if the government is behind this whole competitive sitting trend? They want us to be lazy and complacent so we don't question their actions. It's li... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html |
8619d672eefa-0 | .ipynb
.pdf
Two-Player Dungeons & Dragons
Contents
Import LangChain related modules
DialogueAgent class
DialogueSimulator class
Define roles and quest
Ask an LLM to add detail to the game description
Protagonist and dungeon master system messages
Use an LLM to create an elaborate quest description
Main Loop
Two-Playe... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
8619d672eefa-1 | 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... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
8619d672eefa-2 | 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, mes... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
8619d672eefa-3 | Speak directly to {storyteller_name}.
Do not add anything else."""
)
]
storyteller_description = ChatOpenAI(temperature=1.0)(storyteller_specifier_prompt).content
print('Protagonist Description:')
print(protagonist_description)
print('Storyteller Description:')
print(storyteller_description)
Protagonist... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
8619d672eefa-4 | 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, {prot... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
8619d672eefa-5 | 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 heavil... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
8619d672eefa-6 | 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 lo... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
8619d672eefa-7 | (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... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
81071e4ff1ab-0 | .ipynb
.pdf
Multi-agent decentralized speaker selection
Contents
Import LangChain related modules
DialogueAgent and DialogueSimulator classes
BiddingDialogueAgent class
Define participants and debate topic
Generate system messages
Output parser for bids
Generate bidding system message
Use an LLM to create an elaborat... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-1 | 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
... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-2 | return speaker.name, message
BiddingDialogueAgent class#
We define a subclass of DialogueAgent that has a bid() method that produces a bid given the message history and the most recent message.
class BiddingDialogueAgent(DialogueAgent):
def __init__(
self,
name,
system_message: SystemMessage... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-3 | Speak directly to {character_name}.
Do not add anything else."""
)
]
character_description = ChatOpenAI(temperature=1.0)(character_specifier_prompt).content
return character_description
def generate_character_header(character_name, character_description):
return f"""{game_descrip... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-4 | for character_name, character_description, character_header, character_system_message in zip(character_names, character_descriptions, character_headers, character_system_messages):
print(f'\n\n{character_name} Description:')
print(f'\n{character_description}')
print(f'\n{character_header}')
print(f'\n{c... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-5 | Your goal is to be as creative as possible and make the voters think you are the best candidate.
You will speak in the style of Donald Trump, and exaggerate their personality.
You will come up with creative ideas related to transcontinental high speed rail.
Do not say the same things over and over again.
Speak in the f... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-6 | Your name is Kanye West.
You are a presidential candidate.
Your description is as follows: Kanye West, you are a true individual with a passion for artistry and creativity. You are known for your bold ideas and willingness to take risks. Your determination to break barriers and push boundaries makes you a charismatic a... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-7 | Here is the topic for the presidential debate: transcontinental high speed rail.
The presidential candidates are: Donald Trump, Kanye West, Elizabeth Warren.
Your name is Elizabeth Warren.
You are a presidential candidate.
Your description is as follows: Senator Warren, you are a fearless leader who fights for the litt... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-8 | output_keys=['bid'],
default_output_key='bid')
Generate bidding system message#
This is inspired by the prompt used in Generative Agents for using an LLM to determine the importance of memories. This will use the formatting instructions from our BidOutputParser.
def generate_character_bidding_template(character_hea... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-9 | ```
{recent_message}
```
Your response should be an integer delimited by angled brackets, like this: <int>.
Do nothing else.
Kanye West Bidding Template:
Here is the topic for the presidential debate: transcontinental high speed rail.
The presidential candidates are: Donald Trump, Kanye West, Elizabeth Warren.
You... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-10 | ```
{message_history}
```
On the scale of 1 to 10, where 1 is not contradictory and 10 is extremely contradictory, rate how contradictory the following message is to your ideas.
```
{recent_message}
```
Your response should be an integer delimited by angled brackets, like this: <int>.
Do nothing else.
Use an LLM t... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-11 | We will define a ask_for_bid function that uses the bid_parser we defined before to parse the agent’s bid. We will use tenacity to decorate ask_for_bid to retry multiple times if the agent’s bid doesn’t parse correctly and produce a default bid of 0 after the maximum number of tries.
@tenacity.retry(stop=tenacity.stop_... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-12 | print('\n')
return idx
Main Loop#
characters = []
for character_name, character_system_message, bidding_template in zip(character_names, character_system_messages, character_bidding_templates):
characters.append(BiddingDialogueAgent(
name=character_name,
system_message=character_system_message,
... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-13 | Bids:
Donald Trump bid: 2
Kanye West bid: 8
Elizabeth Warren bid: 10
Selected: Elizabeth Warren
(Elizabeth Warren): Thank you for the question. As a fearless leader who fights for the little guy, I believe that building a sustainable and inclusive transcontinental high-speed rail is not only necessary for our econom... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-14 | Bids:
Donald Trump bid: 7
Kanye West bid: 1
Elizabeth Warren bid: 1
Selected: Donald Trump
(Donald Trump): Kanye, you're a great artist, but this is about practicality. Solar power is too expensive and unreliable. We need to focus on what works, and that's clean coal. And as for the design, we'll make it beautiful, ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-15 | Kanye West bid: 8
Elizabeth Warren bid: 10
Selected: Elizabeth Warren
(Elizabeth Warren): Thank you, but I disagree. We can't sacrifice the needs of local communities for the sake of speed and profit. We need to find a balance that benefits everyone. And as for profitability, we can't rely solely on private investors.... | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
81071e4ff1ab-16 | Use an LLM to create an elaborate on debate topic
Define the speaker selection function
Main Loop
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html |
5c94e8ea48d7-0 | .ipynb
.pdf
AutoGPT
Contents
Set up tools
Set up memory
Setup model and AutoGPT
Run an example
AutoGPT#
Implementation of https://github.com/Significant-Gravitas/Auto-GPT but with LangChain primitives (LLMs, PromptTemplates, VectorStores, Embeddings, Tools)
Set up tools#
We’ll set up an AutoGPT with a search tool, an... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
5c94e8ea48d7-1 | ai_name="Tom",
ai_role="Assistant",
tools=tools,
llm=ChatOpenAI(temperature=0),
memory=vectorstore.as_retriever()
)
# Set verbose to be true
agent.chain.verbose = True
Run an example#
Here we will make it write a weather report for SF
agent.run(["write a weather report for SF today"])
> Entering new LLM... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
5c94e8ea48d7-2 | 3. read_file: Read file from disk, args json schema: {"file_path": {"title": "File Path", "description": "name of file", "type": "string"}}
4. finish: use this to signal that you have finished all your objectives, args: "response": "final response to let people know you have finished your objectives"
Resources:
1. Inte... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
5c94e8ea48d7-3 | System: This reminds you of these events from your past:
[]
Human: Determine which next command to use, and respond using the format specified above:
> Finished chain.
{
"thoughts": {
"text": "I will start by writing a weather report for San Francisco today. I will use the 'search' command to find the curre... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
5c94e8ea48d7-4 | 3. No user assistance
4. Exclusively use the commands listed in double quotes e.g. "command name"
Commands:
1. search: useful for when you need to answer questions about current events. You should ask targeted questions, args json schema: {"query": {"title": "Query", "type": "string"}}
2. write_file: Write file to disk... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
5c94e8ea48d7-5 | "text": "thought",
"reasoning": "reasoning",
"plan": "- short bulleted\n- list that conveys\n- long-term plan",
"criticism": "constructive self-criticism",
"speak": "thoughts summary to say to user"
},
"command": {
"name": "command name",
"args": {
"ar... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
5c94e8ea48d7-6 | System: This reminds you of these events from your past:
['Assistant Reply: {\n "thoughts": {\n "text": "I will start by writing a weather report for San Francisco today. I will use the \'search\' command to find the current weather conditions.",\n "reasoning": "I need to gather information about the c... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
5c94e8ea48d7-7 | "criticism": "I need to make sure that the information I gather is accurate and up-to-date.",
"speak": "I will use the 'search' command to find the current weather conditions in San Francisco."
},
"command": {
"name": "search",
"args": {
"query": "what is the current weather ... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
5c94e8ea48d7-8 | "args": {
"file_path": "weather_report.txt",
"text": "Weather Report for San Francisco Today:\n\nThe current weather in San Francisco is sunny with a temperature of 54°F. It is expected to remain sunny throughout the day with a high of 62°F and a low of 50°F. There is no chance of precipitation ... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
5c94e8ea48d7-9 | 2. write_file: Write file to disk, args json schema: {"file_path": {"title": "File Path", "description": "name of file", "type": "string"}, "text": {"title": "Text", "description": "text to write to file", "type": "string"}}
3. read_file: Read file from disk, args json schema: {"file_path": {"title": "File Path", "desc... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
5c94e8ea48d7-10 | "args": {
"arg name": "value"
}
}
}
Ensure the response can be parsed by Python json.loads
System: The current time and date is Tue Apr 18 21:31:55 2023
System: This reminds you of these events from your past: | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
5c94e8ea48d7-11 | ['Assistant Reply: {\n "thoughts": {\n "text": "I have found that the current weather in San Francisco is sunny with a temperature of 54°F. I will now write a weather report for San Francisco today using the \'write_file\' command.",\n "reasoning": "I need to write a weather report for San Francisco to... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
5c94e8ea48d7-12 | "text": "Weather Report for San Francisco Today:\\n\\nThe current weather in San Francisco is sunny with a temperature of 54°F. It is expected to remain sunny throughout the day with a high of 62°F and a low of 50°F. There is no chance of precipitation today. It is recommended to wear light clothing and sunscreen if sp... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
5c94e8ea48d7-13 | the current weather conditions in San Francisco\\n- Write a weather report based on the information gathered",\n "criticism": "I need to make sure that the information I gather is accurate and up-to-date.",\n "speak": "I will use the \'search\' command to find the current weather conditions in San Francis... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
5c94e8ea48d7-14 | System: Command write_file returned: File written to successfully.
Human: Determine which next command to use, and respond using the format specified above:
> Finished chain.
{
"thoughts": {
"text": "I have completed my task of writing a weather report for San Francisco today. I will now use the \'finish\' ... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
f978e335bd29-0 | .ipynb
.pdf
BabyAGI with Tools
Contents
Install and Import Required Modules
Connect to the Vector Store
Define the Chains
Run the BabyAGI
BabyAGI with Tools#
This notebook builds on top of baby agi, but shows how you can swap out the execution chain. The previous execution chain was just an LLM which made stuff up. B... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
f978e335bd29-1 | Task creation chain to select new tasks to add to the list
Task prioritization chain to re-prioritize tasks
Execution Chain to execute the tasks
NOTE: in this notebook, the Execution chain will now be an agent.
from langchain.agents import ZeroShotAgent, Tool, AgentExecutor
from langchain import OpenAI, SerpAPIWrapper,... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
f978e335bd29-2 | tool_names = [tool.name for tool in tools]
agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names)
agent_executor = AgentExecutor.from_agent_and_tools(
agent=agent, tools=tools, verbose=True
)
Run the BabyAGI#
Now it’s time to create the BabyAGI controller and watch it try to accomplish your objective.... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
f978e335bd29-3 | 8. Proofread and edit the report
9. Submit the report I now know the final answer
Final Answer: The todo list for writing a weather report for SF today is: 1. Research current weather conditions in San Francisco; 2. Gather data on temperature, humidity, wind speed, and other relevant weather conditions; 3. Analyze data... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
f978e335bd29-4 | > Entering new AgentExecutor chain...
Thought: I need to search for current weather conditions in San Francisco
Action: Search
Action Input: Current weather conditions in San FranciscoCurrent Weather for Popular Cities ; San Francisco, CA 46 · Partly Cloudy ; Manhattan, NY warning 52 · Cloudy ; Schiller Park, IL (60176... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
f978e335bd29-5 | 9: Include relevant data sources in the report;
10: Summarize the weather report in a concise manner;
11: Include a summary of the forecasted weather conditions;
12: Include a summary of the current weather conditions;
13: Include a summary of the historical weather patterns;
14: Include a summary of the potential weat... | https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.