id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
cf420ff1c6b5-3 | context_examples = [
{
"question": "How old am I?",
"context": "I am 30 years old. I live in New York and take the train to work everyday.",
},
{
"question": 'Who won the NFC championship game in 2023?"',
"context": "NFC Championship Game 2023: Philadelphia Eagles 31, San Fra... | https://python.langchain.com/en/latest/use_cases/evaluation/question_answering.html |
cf420ff1c6b5-4 | predictions[i]['id'] = str(i)
predictions[i]['prediction_text'] = predictions[i]['text']
for p in predictions:
del p['text']
new_examples = examples.copy()
for eg in new_examples:
del eg ['question']
del eg['answer']
from evaluate import load
squad_metric = load("squad")
results = squad_metric.compute(
... | https://python.langchain.com/en/latest/use_cases/evaluation/question_answering.html |
4669436a4020-0 | .ipynb
.pdf
SQL Question Answering Benchmarking: Chinook
Contents
Loading the data
Setting up a chain
Make a prediction
Make many predictions
Evaluate performance
SQL Question Answering Benchmarking: Chinook#
Here we go over how to benchmark performance on a question answering task over a SQL database.
It is highly r... | https://python.langchain.com/en/latest/use_cases/evaluation/sql_qa_benchmarking_chinook.html |
4669436a4020-1 | {'question': 'How many employees are there?', 'answer': '8'}
Setting up a chain#
This uses the example Chinook database.
To set it up follow the instructions on https://database.guide/2-sample-databases-sqlite/, placing the .db file in a notebooks folder at the root of this repository.
Note that here we load a simple c... | https://python.langchain.com/en/latest/use_cases/evaluation/sql_qa_benchmarking_chinook.html |
4669436a4020-2 | llm = OpenAI(temperature=0)
eval_chain = QAEvalChain.from_llm(llm)
graded_outputs = eval_chain.evaluate(predicted_dataset, predictions, question_key="question", prediction_key="result")
We can add in the graded output to the predictions dict and then get a count of the grades.
for i, prediction in enumerate(predictions... | https://python.langchain.com/en/latest/use_cases/evaluation/sql_qa_benchmarking_chinook.html |
27047069a9ac-0 | .ipynb
.pdf
Benchmarking Template
Contents
Loading the data
Setting up a chain
Make a prediction
Make many predictions
Evaluate performance
Benchmarking Template#
This is an example notebook that can be used to create a benchmarking notebook for a task of your choice. Evaluation is really hard, and so we greatly welc... | https://python.langchain.com/en/latest/use_cases/evaluation/benchmarking_template.html |
27047069a9ac-1 | # Othertimes you may want to write a for loop to catch errors
Evaluate performance#
Any guide to evaluating performance in a more systematic manner goes here.
previous
Agent VectorDB Question Answering Benchmarking
next
Data Augmented Question Answering
Contents
Loading the data
Setting up a chain
Make a prediction... | https://python.langchain.com/en/latest/use_cases/evaluation/benchmarking_template.html |
8eba690fd3f6-0 | .ipynb
.pdf
Question Answering Benchmarking: Paul Graham Essay
Contents
Loading the data
Setting up a chain
Make a prediction
Make many predictions
Evaluate performance
Question Answering Benchmarking: Paul Graham Essay#
Here we go over how to benchmark performance on a question answering task over a Paul Graham essa... | https://python.langchain.com/en/latest/use_cases/evaluation/qa_benchmarking_pg.html |
8eba690fd3f6-1 | Now we can create a question answering chain.
from langchain.chains import RetrievalQA
from langchain.llms import OpenAI
chain = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type="stuff", retriever=vectorstore.as_retriever(), input_key="question")
Make a prediction#
First, we can make predictions one datapoint at a ... | https://python.langchain.com/en/latest/use_cases/evaluation/qa_benchmarking_pg.html |
8eba690fd3f6-2 | from collections import Counter
Counter([pred['grade'] for pred in predictions])
Counter({' CORRECT': 12, ' INCORRECT': 10})
We can also filter the datapoints to the incorrect examples and look at them.
incorrect = [pred for pred in predictions if pred['grade'] == " INCORRECT"]
incorrect[0]
{'question': 'What did the a... | https://python.langchain.com/en/latest/use_cases/evaluation/qa_benchmarking_pg.html |
a9054b4875e3-0 | .ipynb
.pdf
Data Augmented Question Answering
Contents
Setup
Examples
Evaluate
Evaluate with Other Metrics
Data Augmented Question Answering#
This notebook uses some generic prompts/language models to evaluate an question answering system that uses other sources of data besides what is in the model. For example, this... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
a9054b4875e3-1 | "answer": "Nothing"
}
]
# Generated examples
from langchain.evaluation.qa import QAGenerateChain
example_gen_chain = QAGenerateChain.from_llm(OpenAI())
new_examples = example_gen_chain.apply_and_parse([{"doc": t} for t in texts[:5]])
new_examples
[{'query': 'According to the document, what did Vladimir Putin miscal... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
a9054b4875e3-2 | eval_chain = QAEvalChain.from_llm(llm)
graded_outputs = eval_chain.evaluate(examples, predictions)
for i, eg in enumerate(examples):
print(f"Example {i}:")
print("Question: " + predictions[i]['query'])
print("Real Answer: " + predictions[i]['answer'])
print("Predicted Answer: " + predictions[i]['result'... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
a9054b4875e3-3 | Predicted Answer: I don't know.
Predicted Grade: INCORRECT
Example 4:
Question: How many countries were part of the coalition formed to confront Putin?
Real Answer: 27 members of the European Union, France, Germany, Italy, the United Kingdom, Canada, Japan, Korea, Australia, New Zealand, and many others, even Switzer... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
a9054b4875e3-4 | Predicted Grade: CORRECT
Evaluate with Other Metrics#
In addition to predicting whether the answer is correct or incorrect using a language model, we can also use other metrics to get a more nuanced view on the quality of the answers. To do so, we can use the Critique library, which allows for simple calculation of va... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
a9054b4875e3-5 | for k, v in metrics.items()
}
Finally, we can print out the results. We can see that overall the scores are higher when the output is semantically correct, and also when the output closely matches with the gold-standard answer.
for i, eg in enumerate(examples):
score_string = ", ".join([f"{k}={v['examples'][i]['val... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
a9054b4875e3-6 | Example 2:
Question: According to the document, what did Vladimir Putin miscalculate?
Real Answer: He miscalculated that he could roll into Ukraine and the world would roll over.
Predicted Answer: Putin miscalculated that the world would roll over when he rolled into Ukraine.
Predicted Scores: rouge=0.5185, chrf=0.695... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
a9054b4875e3-7 | Question: What action is the U.S. Department of Justice taking to target Russian oligarchs?
Real Answer: The U.S. Department of Justice is assembling a dedicated task force to go after the crimes of Russian oligarchs and joining with European allies to find and seize their yachts, luxury apartments, and private jets.
P... | https://python.langchain.com/en/latest/use_cases/evaluation/data_augmented_question_answering.html |
9325c9056cd0-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 |
9325c9056cd0-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 |
9325c9056cd0-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 |
9325c9056cd0-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 |
9325c9056cd0-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 |
9325c9056cd0-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 |
9325c9056cd0-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 |
9325c9056cd0-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 |
9325c9056cd0-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 |
9325c9056cd0-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 |
9325c9056cd0-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 |
9325c9056cd0-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 |
6fe2fdb1f741-0 | .ipynb
.pdf
Agent Debates with Tools
Contents
Import LangChain related modules
Import modules related to tools
DialogueAgent and DialogueSimulator classes
DialogueAgentWithTools class
Define roles and topic
Ask an LLM to add detail to the topic description
Generate system messages
Main Loop
Agent Debates with Tools#
... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-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_agent_debate_tools.html |
6fe2fdb1f741-2 | return speaker.name, message
DialogueAgentWithTools class#
We define a DialogueAgentWithTools class that augments DialogueAgent to use tools.
class DialogueAgentWithTools(DialogueAgent):
def __init__(
self,
name: str,
system_message: SystemMessage,
model: ChatOpenAI,
tool_nam... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-3 | 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_pr... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-4 | 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 n... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-5 | 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 i... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-6 | Main Loop#
# we set `top_k_results`=2 as part of the `tool_kwargs` to prevent results from overflowing the context limit
agents = [DialogueAgentWithTools(name=name,
system_message=SystemMessage(content=system_message),
model=ChatOpenAI(
model_name='gpt... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-7 | }
```
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 per... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-8 | }
```
> 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 w... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-9 | }
```
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. McKinsey_Website_Accessibility@mckinsey.com Manufacturing (80%) and technol... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-10 | }
```
> 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. Manufacturing and technology sectors have the highest AI usage among executives. AI and automation in the manufacturing industry pres... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-11 | "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 ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-12 | 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 opportuni... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-13 | "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. McKins... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-14 | }
```
> 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, proc... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-15 | "action_input": "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 impac... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-16 | 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. Furt... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-17 | 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,... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-18 | 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 impa... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-19 | 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 f... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-20 | 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 t... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-21 | 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... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
6fe2fdb1f741-22 | }
```
> 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 so... | https://python.langchain.com/en/latest/use_cases/agent_simulations/two_agent_debate_tools.html |
674d1c941d35-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 |
674d1c941d35-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 |
674d1c941d35-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 |
674d1c941d35-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 |
674d1c941d35-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 |
674d1c941d35-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 |
674d1c941d35-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 |
674d1c941d35-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 |
65c238c981d3-0 | .ipynb
.pdf
Simulated Environment: Gymnasium
Contents
Define the agent
Initialize the simulated environment and agent
Main loop
Simulated Environment: Gymnasium#
For many applications of LLM agents, the environment is real (internet, database, REPL, etc). However, we can also define agents to interact in simulated en... | https://python.langchain.com/en/latest/use_cases/agent_simulations/gymnasium.html |
65c238c981d3-1 | 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
... | https://python.langchain.com/en/latest/use_cases/agent_simulations/gymnasium.html |
65c238c981d3-2 | Initialize the 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, rew... | https://python.langchain.com/en/latest/use_cases/agent_simulations/gymnasium.html |
1ce4bfea6f1a-0 | .ipynb
.pdf
Multi-Agent Simulated Environment: Petting Zoo
Contents
Install pettingzoo and other dependencies
Import modules
GymnasiumAgent
Main loop
PettingZooAgent
Rock, Paper, Scissors
ActionMaskAgent
Tic-Tac-Toe
Texas Hold’em No Limit
Multi-Agent Simulated Environment: Petting Zoo#
In this example, we show how to... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-1 | 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... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-2 | 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 tenacit... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-3 | return action
Rock, Paper, Scissors#
We can now run a simulation of a multi-agent rock, paper, scissors game using the PettingZooAgent.
from pettingzoo.classic import rps_v2
env = rps_v2.env(max_cycles=3, render_mode="human")
agents = {name: PettingZooAgent(name=name, model=ChatOpenAI(temperature=1), env=env) for name ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-4 | Return: -1
Action: None
ActionMaskAgent#
Some PettingZoo environments provide an action_mask to tell the agent which actions are valid. The ActionMaskAgent subclasses PettingZooAgent to use information from the action_mask to select actions.
class ActionMaskAgent(PettingZooAgent):
def __init__(self, name, ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-5 | main(agents, env)
Observation: {'observation': array([[[0, 0],
[0, 0],
[0, 0]],
[[0, 0],
[0, 0],
[0, 0]],
[[0, 0],
[0, 0],
[0, 0]]], dtype=int8), 'action_mask': array([1, 1, 1, 1, 1, 1, 1, 1, 1], dtype=int8)}
Reward: 0
Termination: False
Truncation: False
Re... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-6 | X | - | -
_____|_____|_____
| |
O | - | -
_____|_____|_____
| |
- | - | -
| |
Observation: {'observation': array([[[1, 0],
[0, 1],
[0, 0]],
[[0, 0],
[0, 0],
[0, 0]],
[[0, 0],
[0, 0],
[0, 0]]], d... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-7 | [[0, 0],
[0, 0],
[0, 0]]], dtype=int8), 'action_mask': array([0, 0, 0, 1, 1, 1, 1, 1, 1], dtype=int8)}
Reward: 0
Termination: False
Truncation: False
Return: 0
Action: 3
| |
X | O | -
_____|_____|_____
| |
O | - | -
_____|_____|_____
| | ... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-8 | | |
Observation: {'observation': array([[[0, 1],
[1, 0],
[0, 1]],
[[1, 0],
[0, 1],
[0, 0]],
[[0, 0],
[0, 0],
[0, 0]]], dtype=int8), 'action_mask': array([0, 0, 0, 0, 0, 1, 1, 1, 1], dtype=int8)}
Reward: 0
Termination: False
Truncation: False
Return:... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-9 | X | O | X
_____|_____|_____
| |
O | X | -
_____|_____|_____
| |
X | O | -
| |
Observation: {'observation': array([[[0, 1],
[1, 0],
[0, 1]],
[[1, 0],
[0, 1],
[1, 0]],
[[0, 1],
[0, 0],
[0, 0]]], d... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-10 | Here is an example of a Texas Hold’em No Limit game that uses the ActionMaskAgent.
from pettingzoo.classic import texas_holdem_no_limit_v6
env = texas_holdem_no_limit_v6.env(num_players=4, render_mode="human")
agents = {name: ActionMaskAgent(name=name, model=ChatOpenAI(temperature=0.2), env=env) for name in env.possibl... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-11 | 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0.,
0., 0., 2.], dtype=float32), 'action_mask': array([1, 1, 0, 1, 1], dtype=int8)}
Reward: 0
Termination: False
Truncation: False
Return: 0
Action: 1
Observation: {... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-12 | Reward: 0
Termination: False
Truncation: False
Return: 0
Action: 1
Observation: {'observation': array([0., 0., 0., 0., 0., 0., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 1., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0.... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-13 | 0., 0., 0., 0., 0., 1., 0., 0., 1., 0., 0., 0., 0., 0., 0., 0., 0.,
0., 2., 2.], dtype=float32), 'action_mask': array([1, 1, 1, 1, 1], dtype=int8)}
Reward: 0
Termination: False
Truncation: False
Return: 0
Action: 2
Observation: {'observation': array([0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0., 0... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-14 | 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.],... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-15 | 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: {'observat... | https://python.langchain.com/en/latest/use_cases/agent_simulations/petting_zoo.html |
1ce4bfea6f1a-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 |
1ce4bfea6f1a-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 |
1ce4bfea6f1a-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 |
1ce4bfea6f1a-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 |
baaf20bd4f21-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 |
baaf20bd4f21-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 |
baaf20bd4f21-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 |
baaf20bd4f21-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 |
baaf20bd4f21-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 |
baaf20bd4f21-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 |
baaf20bd4f21-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 |
baaf20bd4f21-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 |
baaf20bd4f21-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 |
baaf20bd4f21-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 |
baaf20bd4f21-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 |
baaf20bd4f21-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 |
baaf20bd4f21-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 |
baaf20bd4f21-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 |
baaf20bd4f21-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 |
baaf20bd4f21-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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.