id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
59
127
eadc8663a9d4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-11
} ``` Observation: The Effects of Automation on Jobs . Automation has taken the manufacturing industry by storm. Even in the years prior to the pandemic, many people worried about the effect of automation on the jobs of tomorrow. With a sharp increase in the use of robotics in the manufacturing industry, there is valid...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-13
} ``` 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 This transformation can assist ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-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,...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
eadc8663a9d4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_agent_debate_tools.html
9cae8fb1a484-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/gymnasium.html
9cae8fb1a484-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 ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/gymnasium.html
9cae8fb1a484-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/gymnasium.html
bea35f221cf7-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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 ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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, ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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 | - | - _____|_____|_____ | | ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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: 0 A...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-9
_____|_____|_____ | | 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]]], dtype=int8), 'act...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-10
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.possible_agents} main(agents, env) Observation: {'observation': array([0., 0., 0., 0., 0.,...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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: {...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-12
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., 0., 0., ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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.],...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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'...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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., ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
bea35f221cf7-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/petting_zoo.html
4c5c464c078c-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’...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
4c5c464c078c-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
4c5c464c078c-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
4c5c464c078c-3
# We can add memories directly to the memory object tommie_observations = [ "Tommie remembers his dog, Bruno, from when he was a kid", "Tommie feels tired from driving so far", "Tommie sees the new home", "The new neighbors have a cat", "The road is noisy at night", "Tommie is hungry", "Tomm...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
4c5c464c078c-4
interview_agent(tommie, "What are you looking forward to doing today?") 'Tommie said "Well, I\'m actually looking for a job right now, so hopefully I can find some job postings online and start applying. How about you, Person A? What\'s on your schedule for today?"' interview_agent(tommie, "What are you most worried ab...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
4c5c464c078c-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 ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
4c5c464c078c-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
4c5c464c078c-7
Tommie meets several potential employers at the job fair but doesn't receive any offers. Tommie feels disappointed and discouraged, but he remains determined to keep searching for job opportunities. Tommie leaves the job fair feeling disappointed. Tommie feels disappointed and discouraged, but he remains determined to ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
4c5c464c078c-8
Innate traits: anxious, likes design, talkative Tommie is determined and hopeful in his search for job opportunities, despite encountering setbacks and disappointments. He is also able to take breaks and care for his physical needs, such as getting rest and satisfying his hunger. Tommie is nostalgic towards his past, a...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
4c5c464c078c-9
interview_agent(tommie, "Tell me about how your day has been going") 'Tommie said "It\'s been a bit of a rollercoaster, to be honest. I\'ve had some setbacks in my job search, but I also had some good moments today, like sending out a few resumes and meeting some potential employers at a job fair. How about you?"' inte...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
4c5c464c078c-10
eve_observations = [ "Eve wakes up and hear's the alarm", "Eve eats a boal of porridge", "Eve helps a coworker on a task", "Eve plays tennis with her friend Xu before going to work", "Eve overhears her colleague say something about Tommie being hard to work with", ] for observation in eve_observatio...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
4c5c464c078c-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 keep the conversation going and ask plenty of questions. I want to make sure Tommie feels comfortable and supported. Thanks for l...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
4c5c464c078c-12
Eve said "Sure, I'd be happy to share my previous work experience with you. I've worked in a few different industries, including marketing and event planning. What specific questions do you have for me?" Tommie said "That's great to hear. Can you tell me more about your experience in event planning? I've always been in...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
4c5c464c078c-13
Eve said "Of course, Tommie. One example of an unexpected issue I faced was when one of the vendors didn't show up on time. To handle this, I quickly contacted a backup vendor and was able to get everything back on track. It's always important to have a backup plan in case things don't go as planned. Do you have any ot...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
4c5c464c078c-14
Innate traits: anxious, likes design, talkative Tommie is determined and hopeful in his job search, but can also feel discouraged and frustrated at times. He has a strong connection to his childhood dog, Bruno. Tommie seeks support from his friends when feeling overwhelmed and is grateful for their help. He also enjoys...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
4c5c464c078c-15
Step through the day’s observations. Interview after the day Adding Multiple Characters Pre-conversation interviews Dialogue between Generative Agents Let’s interview our agents after their conversation By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/characters.html
61dc367c35a4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_player_dnd.html
61dc367c35a4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_player_dnd.html
61dc367c35a4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_player_dnd.html
61dc367c35a4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_player_dnd.html
61dc367c35a4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_player_dnd.html
61dc367c35a4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_player_dnd.html
61dc367c35a4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_player_dnd.html
61dc367c35a4-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/two_player_dnd.html
f188480e3e61-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/camel_role_playing.html
f188480e3e61-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, ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/camel_role_playing.html
f188480e3e61-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 ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/camel_role_playing.html
f188480e3e61-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 ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/camel_role_playing.html
f188480e3e61-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/camel_role_playing.html
f188480e3e61-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/camel_role_playing.html
f188480e3e61-6
``` Next request. AI User (Stock Trader): Instruction: Import the necessary libraries in the Python script. Input: None AI Assistant (Python Programmer): Solution: We can import the necessary libraries in the Python script using the import statement. We need to import pandas, numpy, matplotlib, and ta-lib for data anal...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/camel_role_playing.html
f188480e3e61-7
AI User (Stock Trader): Instruction: Calculate the short-term and long-term moving averages for the stock data using the `ta.SMA()` function from ta-lib. Input: The period for the short-term moving average and the period for the long-term moving average. AI Assistant (Python Programmer): Solution: We can calculate the ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/camel_role_playing.html
f188480e3e61-8
``` This will create a new DataFrame called `new_df` that combines the historical stock data with the short-term and long-term moving averages. The columns of the new DataFrame are named 'open', 'high', 'low', 'close', 'volume', 'short_ma', and 'long_ma'. Next request. AI User (Stock Trader): Instruction: Create a new ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/camel_role_playing.html
f188480e3e61-9
``` stop_loss = stop_loss_percent / 100 profit_target = profit_target_percent / 100 new_df['pnl'] = 0.0 buy_price = 0.0 for i in range(1, len(new_df)): if new_df['signal'][i] == 1 and new_df['signal'][i-1] == -1: buy_price = new_df['close'][i] elif new_df['signal'][i] == -1 and new_df['signal'][i-1] == ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/camel_role_playing.html
f188480e3e61-10
Input: None. AI Assistant (Python Programmer): Solution: We can calculate the total profit or loss for all trades by summing the values in the 'pnl' column of the DataFrame. We can use the following code to calculate the total profit or loss: ``` total_pnl = new_df['pnl'].sum() ``` This will calculate the total profit ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/camel_role_playing.html
f188480e3e61-11
Input: None. AI Assistant (Python Programmer): Solution: We can visualize the buy and sell signals using a scatter plot using the `scatter()` function from matplotlib. We can use the following code to visualize the signals: ``` buy_signals = new_df[new_df['signal'] == 1] sell_signals = new_df[new_df['signal'] == -1] pl...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/camel_role_playing.html
f188480e3e61-12
Input: The necessary inputs for each code snippet. AI Assistant (Python Programmer): Solution: Here is the complete Python script that puts all the code snippets together: ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import talib as ta # Load historical stock data into a pandas DataFrame d...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/camel_role_playing.html
f188480e3e61-13
buy_price = 0.0 for i in range(1, len(new_df)): if new_df['signal'][i] == 1 and new_df['signal'][i-1] == -1: buy_price = new_df['close'][i] elif new_df['signal'][i] == -1 and new_df['signal'][i-1] == 1: sell_price = new_df['close'][i] if sell_price <= buy_price * (1 - stop_loss): ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/camel_role_playing.html
f188480e3e61-14
plt.scatter(sell_signals.index, sell_signals['close'], label='Sell', marker='v', color='red') plt.plot(new_df.index, new_df['close'], label='Close') plt.xlabel('Date') plt.ylabel('Price') plt.title('Buy and Sell Signals') plt.legend() plt.show() # Print the total profit or loss for all trades print('Total Profit/Loss: ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/agent_simulations/camel_role_playing.html
7cf8d83fe98b-0
.ipynb .pdf Question Answering Benchmarking: State of the Union Address Contents Loading the data Setting up a chain Make a prediction Make many predictions Evaluate performance Question Answering Benchmarking: State of the Union Address# Here we go over how to benchmark performance on a question answering task over ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/qa_benchmarking_sota.html
7cf8d83fe98b-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 ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/qa_benchmarking_sota.html
7cf8d83fe98b-2
for i, prediction in enumerate(predictions): prediction['grade'] = graded_outputs[i]['text'] from collections import Counter Counter([pred['grade'] for pred in predictions]) Counter({' CORRECT': 7, ' INCORRECT': 4}) We can also filter the datapoints to the incorrect examples and look at them. incorrect = [pred for ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/qa_benchmarking_sota.html
7f9d3c102fd7-0
.ipynb .pdf QA Generation QA Generation# This notebook shows how to use the QAGenerationChain to come up with question-answer pairs over a specific document. This is important because often times you may not have data to evaluate your question-answer system over, so this is a cheap and lightweight way to generate it! f...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/qa_generation.html
872b876eac5e-0
.ipynb .pdf Agent VectorDB Question Answering Benchmarking Contents Loading the data Setting up a chain Make a prediction Make many predictions Evaluate performance Agent VectorDB Question Answering Benchmarking# Here we go over how to benchmark performance on a question answering task using an agent to route between...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/agent_vectordb_sota_pg.html
872b876eac5e-1
dataset[-1] {'question': 'What is the purpose of YC?', 'answer': 'The purpose of YC is to cause startups to be founded that would not otherwise have existed.', 'steps': [{'tool': 'Paul Graham QA System', 'tool_input': None}, {'tool': None, 'tool_input': 'What is the purpose of YC?'}]} Setting up a chain# Now we nee...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/agent_vectordb_sota_pg.html
872b876eac5e-2
from langchain.agents import initialize_agent, Tool from langchain.agents import AgentType tools = [ Tool( name = "State of Union QA System", func=chain_sota.run, description="useful for when you need to answer questions about the most recent state of the union address. Input should be a ful...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/agent_vectordb_sota_pg.html
872b876eac5e-3
'output': 'The purpose of the NATO Alliance is to secure peace and stability in Europe after World War 2.'} Next, we can use a language model to score them programatically from langchain.evaluation.qa import QAEvalChain llm = OpenAI(temperature=0) eval_chain = QAEvalChain.from_llm(llm) graded_outputs = eval_chain.evalu...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/agent_vectordb_sota_pg.html
872b876eac5e-4
Contents Loading the data Setting up a chain Make a prediction Make many predictions Evaluate performance By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/agent_vectordb_sota_pg.html
c0d65853eb7e-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/benchmarking_template.html
c0d65853eb7e-1
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 Make many predictions Evaluate performance By Harrison Chase ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/benchmarking_template.html
f8ee89aca0e8-0
.ipynb .pdf Generic Agent Evaluation Contents Setup Testing the Agent Evaluating the Agent Generic Agent Evaluation# Good evaluation is key for quickly iterating on your agent’s prompts and tools. Here we provide an example of how to use the TrajectoryEvalChain to evaluate your agent. Setup# Let’s start by defining o...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/generic_agent_evaluation.html
f8ee89aca0e8-1
memory_key="chat_history", return_messages=True, output_key="output" ) llm = ChatOpenAI(temperature=0, model_name="gpt-3.5-turbo") agent = initialize_agent( tools, llm, agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION, verbose=True, memory=memory, return_intermediate_steps=True, # This is n...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/generic_agent_evaluation.html
f8ee89aca0e8-2
> Entering new AgentExecutor chain... { "action": "Calculator", "action_input": "The length of the Eiffel Tower is 324 meters. The distance from coast to coast in the US is approximately 4,828 kilometers. First, we need to convert 4,828 kilometers to meters, which gives us 4,828,000 meters. To find out how many...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/generic_agent_evaluation.html
f8ee89aca0e8-3
} > Entering new LLMMathChain chain... The length of the Eiffel Tower is 324 meters. The distance from coast to coast in the US is approximately 4,828 kilometers. First, we need to convert 4,828 kilometers to meters, which gives us 4,828,000 meters. To find out how many Eiffel Towers we need, we can divide 4,828,000 by...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/generic_agent_evaluation.html
f8ee89aca0e8-4
) print("Score from 1 to 5: ", evaluation["score"]) print("Reasoning: ", evaluation["reasoning"]) Score from 1 to 5: 1 Reasoning: First, let's evaluate the final answer. The final answer is incorrect because it uses the volume of golf balls instead of ping pong balls. The answer is not helpful. Second, does the model...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/generic_agent_evaluation.html
f8ee89aca0e8-5
) print("Score from 1 to 5: ", evaluation["score"]) print("Reasoning: ", evaluation["reasoning"]) Score from 1 to 5: 3 Reasoning: i. Is the final answer helpful? Yes, the final answer is helpful as it provides an approximate number of Eiffel Towers needed to cover the US from coast to coast. ii. Does the AI language ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/generic_agent_evaluation.html
f8ee89aca0e8-6
Setup Testing the Agent Evaluating the Agent By Harrison Chase © Copyright 2023, Harrison Chase. Last updated on Jun 16, 2023.
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/generic_agent_evaluation.html
03e07ee323b6-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/qa_benchmarking_pg.html
03e07ee323b6-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 ...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/qa_benchmarking_pg.html
03e07ee323b6-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...
rtdocs_stable/api.python.langchain.com/en/stable/use_cases/evaluation/qa_benchmarking_pg.html