id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
49
115
5fd2c6d05340-1
Enable tracing if desired# #import os #os.environ["LANGCHAIN_HANDLER"] = "langchain" #os.environ["LANGCHAIN_SESSION"] = "default" # Make sure this session actually exists. Tools# Three tools are provided for this simple agent: ItemLookup: for finding the q-number of an item PropertyLookup: for finding the p-number of ...
https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html
5fd2c6d05340-2
else: raise ValueError("entity_type must be either 'property' or 'item'") params = { "action": "query", "list": "search", "srsearch": search, "srnamespace": srnamespace, "srlimit": 1, "srqiprofile": srqiprofile, "srwhat": 'text', ...
https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html
5fd2c6d05340-3
headers = { 'Accept': 'application/json' } if wikidata_user_agent_header is not None: headers['User-Agent'] = wikidata_user_agent_header response = requests.get(url, headers=headers, params={'query': query, 'format': 'json'}) if response.status_code != 200: return "That query fai...
https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html
5fd2c6d05340-4
name = "SparqlQueryRunner", func=run_sparql, description="useful for getting results from a wikibase" ) ] Prompts# # Set up the base template template = """ Answer the following questions by running a sparql query against a wikibase where the p and q items are completely unknown to you. You wil...
https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html
5fd2c6d05340-5
Question: {input} {agent_scratchpad}""" # Set up a prompt template class CustomPromptTemplate(StringPromptTemplate): # The template to use template: str # The list of tools available tools: List[Tool] def format(self, **kwargs) -> str: # Get the intermediate steps (AgentAction, Observat...
https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html
5fd2c6d05340-6
if "Final Answer:" in llm_output: return AgentFinish( # Return values is generally always a dictionary with a single `output` key # It is not recommended to try anything else at the moment :) return_values={"output": llm_output.split("Final Answer:")[-1].strip...
https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html
5fd2c6d05340-7
# agent_executor.agent.llm_chain.verbose = True agent_executor.run("How many children did J.S. Bach have?") > Entering new AgentExecutor chain... Thought: I need to find the Q number for J.S. Bach. Action: ItemLookup Action Input: J.S. Bach Observation:Q1339I need to find the P number for children. Action: PropertyLook...
https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html
5fd2c6d05340-8
Action: PropertyLookup Action Input: Basketball-Reference.com NBA player ID Observation:P2685Now that I have both the Q-number for Hakeem Olajuwon (Q273256) and the P-number for the Basketball-Reference.com NBA player ID property (P2685), I can run a SPARQL query to get the ID value. Action: SparqlQueryRunner Action In...
https://python.langchain.com/en/latest/use_cases/agents/wikibase_agent.html
7ccae3bc4bf8-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
7ccae3bc4bf8-1
""" self.prefix = f'\n{self.name}:' def send(self) -> str: """ Applies the chatmodel to the message history and returns the message string """ message = self.model( [self.system_message, HumanMessage(content=self.message_history+self...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html
7ccae3bc4bf8-2
# 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/en/latest/use_cases/agent_simulations/multi_player_dnd.html
7ccae3bc4bf8-3
return character_description def 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 tak...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html
7ccae3bc4bf8-4
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 ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html
7ccae3bc4bf8-5
Hermione Granger Description: Hermione Granger, you are the brightest witch of your age. Your quick wit and vast knowledge are essential in our quest to find the horcruxes. Trust in your abilities and remember, knowledge is power. Argus Filch Description: Argus Filch, you are a bitter and cruel caretaker of the Hogwart...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html
7ccae3bc4bf8-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
7ccae3bc4bf8-7
) simulator.reset(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): You have discovered that one of Voldemort's horcruxes is hidden deep...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html
7ccae3bc4bf8-8
(Hermione Granger): I take out my wand and cast a spell to conjure a small boat. We can use it to reach the center of the pond and retrieve the horcrux. But we need to be careful, there could be traps or other obstacles in our way. Ron, Harry, let's row the boat while Argus Filch keeps watch from the shore. (Dungeon Ma...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html
7ccae3bc4bf8-9
(Dungeon Master): As you make your way back to Hogwarts, you hear a loud roar coming from the Forbidden Forest. It sounds like a werewolf. You must hurry before it catches up to you. You arrive at Dumbledore's office and he tells you that the next horcrux is hidden in a dangerous location. Are you ready for the next ch...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html
7ccae3bc4bf8-10
(Argus Filch): I'll make sure to keep watch outside the bank while you all go in. I may not be able to help with the magic, but I can make sure no one interferes with our mission. We can't let anyone stop us from finding that horcrux and defeating Voldemort. Let's go! (Dungeon Master): As you approach Gringotts Bank, y...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html
7ccae3bc4bf8-11
(Dungeon Master): As you make your way back to Hogwarts, you hear a loud explosion coming from the direction of Hogsmeade. You arrive to find that Death Eaters have attacked the village and are wreaking havoc. You must fight off the Death Eaters and protect the innocent villagers. Are you ready to face this unexpected ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html
3298f07d825a-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
3298f07d825a-1
and returns the message string """ message = self.model( [self.system_message, HumanMessage(content=self.message_history+self.prefix)]) return message.content def receive(self, name: str, message: str) -> None: """ Concatenates {message}...
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html
3298f07d825a-2
for receiver in self.agents: receiver.receive(speaker.name, message) # 4. increment time self._step += 1 return speaker.name, message Define roles and quest# protagonist_name = "Harry Potter" storyteller_name = "Dungeon Master" quest = "Find all of Lord ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html
3298f07d825a-3
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 Description: Harry Potter, you are a brave an...
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html
3298f07d825a-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
3298f07d825a-5
print(f"Detailed quest:\n{specified_quest}\n") Original quest: Find all of Lord Voldemort's seven horcruxes. Detailed quest: Harry Potter, you must journey to the hidden cave where one of Voldemort's horcruxes resides. The cave is guarded by enchanted creatures and curses that can only be lifted by a unique magical pot...
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html
3298f07d825a-6
(Harry Potter): I take a deep breath and focus on the task at hand. I search my bag for any potions or ingredients that may be useful in brewing the unique magical potion. If I don't have any, I will search the surrounding area for any plants or herbs that may be useful. Once I have all the necessary ingredients, I wil...
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html
3298f07d825a-7
It is your turn, Dungeon Master. (Dungeon Master): As you consult your map, you notice that the next horcrux is located in a heavily guarded fortress. The fortress is surrounded by a moat filled with dangerous creatures and the entrance is protected by powerful spells. You will need to come up with a plan to get past t...
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html
3298f07d825a-8
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 By Harrison Chase © Copyright 2023, Har...
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html
4ea53ce4f5ac-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
4ea53ce4f5ac-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
4ea53ce4f5ac-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
4ea53ce4f5ac-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
4ea53ce4f5ac-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
4ea53ce4f5ac-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
4ea53ce4f5ac-6
Your name is Kanye West. You are a presidential candidate. Your description is as follows: Kanye West, you are a creative visionary who is unafraid to speak your mind. Your innovative approach to art and music has made you one of the most influential figures of our time. You bring a bold and unconventional perspective ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html
4ea53ce4f5ac-7
Your name is Elizabeth Warren. You are a presidential candidate. Your description is as follows: Elizabeth Warren, you are a fierce advocate for the middle class and a champion of progressive policies. Your tenacity and unwavering dedication to fighting for what you believe in have inspired many. Your policies are guid...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html
4ea53ce4f5ac-8
Do not add anything else. Output parser for bids# We ask the agents to output a bid to speak. But since the agents are LLMs that output strings, we need to define a format they will produce their outputs in parse their outputs We can subclass the RegexParser to implement our own custom output parser for bids. clas...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html
4ea53ce4f5ac-9
Your name is Donald Trump. You are a presidential candidate. Your description is as follows: Donald Trump, you exude confidence and a bold personality. You are known for your unpredictability and your desire for greatness. You often speak your mind without reservation, which can be a strength but also a weakness. You a...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html
4ea53ce4f5ac-10
Do nothing else. Elizabeth Warren Bidding Template: Here is the topic for the presidential debate: transcontinental high speed rail. The presidential candidates are: Donald Trump, Kanye West, Elizabeth Warren. Your name is Elizabeth Warren. You are a presidential candidate. Your description is as follows: Elizabet...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html
4ea53ce4f5ac-11
specified_topic = ChatOpenAI(temperature=1.0)(topic_specifier_prompt).content print(f"Original topic:\n{topic}\n") print(f"Detailed topic:\n{specified_topic}\n") Original topic: transcontinental high speed rail Detailed topic: Candidates, with the rise of autonomous technologies, we must address the problem of how to i...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html
4ea53ce4f5ac-12
bids = [] for agent in agents: bid = ask_for_bid(agent) bids.append(bid) # randomly select among multiple agents with the same bid max_value = np.max(bids) max_indices = np.where(bids == max_value)[0] idx = np.random.choice(max_indices) print('Bids:') for i, (bi...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html
4ea53ce4f5ac-13
Bids: Donald Trump bid: 8 Kanye West bid: 2 Elizabeth Warren bid: 1 Selected: Donald Trump (Donald Trump): Let me tell you, folks, I have the best plan for integrating autonomous vehicles into our high speed rail system. We're going to use the latest technology, the best technology, to ensure safety and efficiency. ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html
4ea53ce4f5ac-14
Kanye West bid: 2 Elizabeth Warren bid: 1 Selected: Donald Trump (Donald Trump): Let me tell you, Elizabeth, safety is important, but we also need to think about innovation and progress. We can't let fear hold us back from achieving greatness. That's why I propose a competition, a race to see which company can create ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html
4ea53ce4f5ac-15
Kanye West bid: 2 Elizabeth Warren bid: 1 Selected: Donald Trump (Donald Trump): Kanye, I hear what you're saying, but let's not forget about the importance of luxury and comfort. We need to make sure that our high speed rail system is not only accessible, but also enjoyable. That's why I propose that we have differen...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html
4ea53ce4f5ac-16
Kanye West bid: 1 Elizabeth Warren bid: 1 Selected: Donald Trump (Donald Trump): Let me tell you, Elizabeth, I agree that we need to think about the environment, but we also need to think about the economy. That's why I propose that we use American-made materials and labor to build this high speed rail system. We're g...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html
4ea53ce4f5ac-17
Kanye West bid: 1 Elizabeth Warren bid: 1 Selected: Donald Trump (Donald Trump): Let me tell you, Elizabeth, safety is important, but we also need to think about efficiency and speed. That's why I propose that we use the latest technology, such as artificial intelligence and machine learning, to monitor and maintain o...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_bidding.html
791edcf62c0e-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
791edcf62c0e-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
791edcf62c0e-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
791edcf62c0e-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
791edcf62c0e-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
791edcf62c0e-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
791edcf62c0e-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
791edcf62c0e-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
791edcf62c0e-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
791edcf62c0e-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
791edcf62c0e-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
791edcf62c0e-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
791edcf62c0e-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
791edcf62c0e-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
791edcf62c0e-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
791edcf62c0e-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
d371937f72a6-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
2b65bb057372-0
.ipynb .pdf Generative Agents in LangChain Contents Generative Agent Memory Components Memory Lifecycle Create a Generative Character Pre-Interview with Character Step through the day’s observations. Interview after the day Adding Multiple Characters Pre-conversation interviews Dialogue between Generative Agents Let’...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
2b65bb057372-1
Memories are retrieved using a weighted sum of salience, recency, and importance. You can review the definitions of the GenerativeAgent and GenerativeAgentMemory in the reference documentation for the following imports, focusing on add_memory and summarize_related_memories methods. from langchain.experimental.generativ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
2b65bb057372-2
def create_new_memory_retriever(): """Create a new vector store retriever unique to the agent.""" # Define your embedding model embeddings_model = OpenAIEmbeddings() # Initialize the vectorstore as empty embedding_size = 1536 index = faiss.IndexFlatL2(embedding_size) vectorstore = FAISS(embe...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
2b65bb057372-3
"Tommie remembers his dog, Bruno, from when he was a kid", "Tommie feels tired from driving so far", "Tommie sees the new home", "The new neighbors have a cat", "The road is noisy at night", "Tommie is hungry", "Tommie tries to get some rest.", ] for observation in tommie_observations: tommi...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
2b65bb057372-4
interview_agent(tommie, "What are you looking forward to doing today?") 'Tommie said "Well, today I\'m mostly focused on getting settled into my new home. But once that\'s taken care of, I\'m looking forward to exploring the neighborhood and finding some new design inspiration. What about you?"' interview_agent(tommie,...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
2b65bb057372-5
"Tommie leaves the job fair feeling disappointed.", "Tommie stops by a local diner to grab some lunch.", "The service is slow, and Tommie has to wait for 30 minutes to get his food.", "Tommie overhears a conversation at the next table about a job opening.", "Tommie asks the diners about the job opening ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
2b65bb057372-6
print(colored(observation, "green"), reaction) if ((i+1) % 20) == 0: print('*'*40) print(colored(f"After {i+1} observations, Tommie's summary is:\n{tommie.get_summary(force_refresh=True)}", "blue")) print('*'*40) Tommie wakes up to the sound of a noisy construction site outside his window. T...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
2b65bb057372-7
The line to get in is long, and Tommie has to wait for an hour. Tommie sighs and looks around, feeling impatient and frustrated. Tommie meets several potential employers at the job fair but doesn't receive any offers. Tommie Tommie's shoulders slump and he sighs, feeling discouraged. Tommie leaves the job fair feeling ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
2b65bb057372-8
Name: Tommie (age: 25) Innate traits: anxious, likes design, talkative Tommie is hopeful and proactive in his job search, but easily becomes discouraged when faced with setbacks. He enjoys spending time outdoors and interacting with animals. Tommie is also productive and enjoys updating his resume and cover letter. He ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
2b65bb057372-9
interview_agent(tommie, "Tell me about how your day has been going") 'Tommie said "Well, it\'s been a bit of a mixed day. I\'ve had some setbacks in my job search, but I also had some fun playing frisbee and spending time outdoors. How about you?"' interview_agent(tommie, "How do you feel about coffee?") 'Tommie said "...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
2b65bb057372-10
eve_observations = [ "Eve overhears her colleague say something about a new client being hard to work with", "Eve wakes up and hear's the alarm", "Eve eats a boal of porridge", "Eve helps a coworker on a task", "Eve plays tennis with her friend Xu before going to work", "Eve overhears her collea...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
2b65bb057372-11
interview_agent(eve, "You'll have to ask him. He may be a bit anxious, so I'd appreciate it if you keep the conversation going and ask as many questions as possible.") 'Eve said "Sure, I can definitely ask him a lot of questions to keep the conversation going. Thanks for the heads up about his anxiety."' Dialogue betwe...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
2b65bb057372-12
Eve said "Sure, Tommie. I found that networking and reaching out to professionals in my field was really helpful. I also made sure to tailor my resume and cover letter to each job I applied to. Do you have any specific questions about those strategies?" Tommie said "Thank you, Eve. That's really helpful advice. Did you...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
2b65bb057372-13
Name: Tommie (age: 25) Innate traits: anxious, likes design, talkative Tommie is a hopeful and proactive individual who is searching for a job. He becomes discouraged when he doesn't receive any offers or positive responses, but he tries to stay productive and calm by updating his resume, going for walks, and talking t...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
2b65bb057372-14
interview_agent(eve, "What do you wish you would have said to Tommie?") 'Eve said "Well, I think I covered most of the topics Tommie was interested in, but if I had to add one thing, it would be to make sure to follow up with any connections you make during your job search. It\'s important to maintain those relationshi...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html