average. The x-axis represents the date and the y-axis represents the price. The chart also includes a legend that labels each line. Next request.            AI User (Stock Trader):        Instruction: Visualize the buy and sell signals using a scatter plot.    Input: None.            AI Assistant (Python Programmer):        Solution: We can visualize the buy and sell signals using a scatter plot using the `scatter()` function from matplotlib. We can use the following code to visualize the signals:        ```    buy_signals = new_df[new_df['signal'] == 1]    sell_signals = new_df[new_df['signal'] == -1]        plt.figure(figsize=(12,6))    plt.scatter(buy_signals.index, buy_signals['close'], label='Buy', marker='^', color='green')    plt.scatter(sell_signals.index, sell_signals['close'], label='Sell', marker='v', color='red')    plt.plot(new_df.index, new_df['close'], label='Close')    plt.xlabel('Date')    plt.ylabel('Price')    plt.title('Buy and Sell Signals')    plt.legend()    plt.show()    ```        This will create a scatter plot that visualizes the buy and sell signals. The x-axis represents the date and the y-axis represents the price. The chart also includes a legend that labels each point. Next request.            AI User (Stock Trader):        Instruction: Print the total profit or loss for all trades.    Input: None.


Print the total profit or loss for all trades.    Input: None.            AI Assistant (Python Programmer):        Solution: We can print the total profit or loss for all trades using the `print()` function. We can use the following code to print the total profit or loss:        ```    print('Total Profit/Loss: {:.2%}'.format(total_pnl))    ```        This will print the total profit or loss for all trades in percentage format with two decimal places. Next request.            AI User (Stock Trader):        Instruction: Finalize the code by putting all the code snippets together in a single Python script.    Input: The necessary inputs for each code snippet.            AI Assistant (Python Programmer):        Solution: Here is the complete Python script that puts all the code snippets together:        ```    import pandas as pd    import numpy as np    import matplotlib.pyplot as plt    import talib as ta        # Load historical stock data into a pandas DataFrame    df = pd.read_csv('path/to/csv/file.csv')        # Preprocess the historical stock data    df = df.set_index('date')    df = df.sort_index(ascending=True)        # Calculate the short-term and long-term moving averages    short_period = 10    long_period = 30    short_ma = ta.SMA(df['close'], timeperiod=short_period)    long_ma =


= ta.SMA(df['close'], timeperiod=short_period)    long_ma = ta.SMA(df['close'], timeperiod=long_period)        # Create a new DataFrame that combines the historical stock data with the short-term and long-term moving averages    new_df = pd.concat([df, short_ma, long_ma], axis=1)    new_df.columns = ['open', 'high', 'low', 'close', 'volume', 'short_ma', 'long_ma']        # Create a new column in the DataFrame that indicates when to buy or sell the stock based on the crossover of the short-term and long-term moving averages    new_df['signal'] = np.where(new_df['short_ma'] > new_df['long_ma'], 1, -1)        # Create a new column in the DataFrame that indicates the profit or loss for each trade based on the buy and sell signals and the defined stop loss and profit target    stop_loss_percent = 5    profit_target_percent = 10    stop_loss = stop_loss_percent / 100    profit_target = profit_target_percent / 100    new_df['pnl'] = 0.0    buy_price = 0.0    for i in range(1, len(new_df)):        if new_df['signal'][i] == 1 and new_df['signal'][i-1] == -1:            buy_price = new_df['close'][i]        elif new_df['signal'][i] == -1 and new_df['signal'][i-1] == 1:            sell_price =


== 1:            sell_price = new_df['close'][i]            if sell_price <= buy_price * (1 - stop_loss):                new_df['pnl'][i] = -stop_loss            elif sell_price >= buy_price * (1 + profit_target):                new_df['pnl'][i] = profit_target            else:                new_df['pnl'][i] = (sell_price - buy_price) / buy_price        # Calculate the total profit or loss for all trades    total_pnl = new_df['pnl'].sum()        # Visualize the stock data, short-term moving average, and long-term moving average using a line chart    plt.figure(figsize=(12,6))    plt.plot(new_df.index, new_df['close'], label='Close')    plt.plot(new_df.index, new_df['short_ma'], label='Short MA')    plt.plot(new_df.index, new_df['long_ma'], label='Long MA')    plt.xlabel('Date')    plt.ylabel('Price')    plt.title('Stock Data with Moving Averages')    plt.legend()    plt.show()        # Visualize the buy and sell signals using a scatter plot    buy_signals = new_df[new_df['signal'] == 1]    sell_signals = new_df[new_df['signal'] == -1]


sell_signals = new_df[new_df['signal'] == -1]    plt.figure(figsize=(12,6))    plt.scatter(buy_signals.index, buy_signals['close'], label='Buy', marker='^', color='green')    plt.scatter(sell_signals.index, sell_signals['close'], label='Sell', marker='v', color='red')    plt.plot(new_df.index, new_df['close'], label='Close')    plt.xlabel('Date')    plt.ylabel('Price')    plt.title('Buy and Sell Signals')    plt.legend()    plt.show()        # Print the total profit or loss for all trades    print('Total Profit/Loss: {:.2%}'.format(total_pnl))    ```        You need to replace the path/to/csv/file.csv with the actual path to the CSV file containing the historical stock data. You can also adjust the short_period, long_period, stop_loss_percent, and profit_target_percent variables to suit your needs.            AI User (Stock Trader):        <CAMEL_TASK_DONE>            AI Assistant (Python Programmer):        Great! Let me know if you need any further assistance.        PreviousAgent simulationsNextGenerative Agents in LangChainImport LangChain related modulesDefine a CAMEL agent helper classSetup OpenAI API key and roles and task for role-playingCreate a task specify agent for brainstorming and get the specified taskCreate inception prompts for AI assistant and AI user for role-playingCreate a helper helper to get system messages for AI assistant and AI user from role names and the taskCreate AI assistant agent and AI user agent from obtained system


and AI user from role names and the taskCreate AI assistant agent and AI user agent from obtained system messagesStart role-playing session to solve the task!CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


Simulated Environment: Gymnasium | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsCAMEL Role-Playing Autonomous Cooperative AgentsGenerative Agents in LangChainSimulated Environment: GymnasiumMulti-Player Dungeons & DragonsMulti-agent authoritarian speaker selectionMulti-agent decentralized speaker selectionMulti-Agent Simulated Environment: Petting ZooAgent Debates with ToolsTwo-Player Dungeons & DragonsAgentsAutonomous (long-running) agentsMulti-modalUse casesAgent simulationsSimulated Environment: GymnasiumOn this pageSimulated Environment: GymnasiumFor many applications of LLM agents, the environment is real (internet, database, REPL, etc). However, we can also define agents to interact in simulated environments like text-based games. This is an example of how to create a simple agent-environment interaction loop with Gymnasium (formerly OpenAI Gym).pip install gymnasiumimport gymnasium as gymimport inspectimport tenacityfrom langchain.chat_models import ChatOpenAIfrom langchain.schema import (    AIMessage,    HumanMessage,    SystemMessage,    BaseMessage,)from langchain.output_parsers import RegexParserDefine the agentâ€‹class GymnasiumAgent:    @classmethod    def get_docs(cls, env):        return env.unwrapped.__doc__    def __init__(self, model, env):        self.model = model        self.env = env        self.docs = self.get_docs(env)        self.instructions = """Your goal is to maximize your return, i.e. the sum of the rewards you receive.I


"""Your goal is to maximize your return, i.e. the sum of the rewards you receive.I will give you an observation, reward, terminiation flag, truncation flag, and the return so far, formatted as:Observation: <observation>Reward: <reward>Termination: <termination>Truncation: <truncation>Return: <sum_of_rewards>You will respond with an action, formatted as:Action: <action>where you replace <action> with your actual action.Do nothing else but return the action."""        self.action_parser = RegexParser(            regex=r"Action: (.*)", output_keys=["action"], default_output_key="action"        )        self.message_history = []        self.ret = 0    def random_action(self):        action = self.env.action_space.sample()        return action    def reset(self):        self.message_history = [            SystemMessage(content=self.docs),            SystemMessage(content=self.instructions),        ]    def observe(self, obs, rew=0, term=False, trunc=False, info=None):        self.ret += rew        obs_message = f"""Observation: {obs}Reward: {rew}Termination: {term}Truncation: {trunc}Return: {self.ret}        """        self.message_history.append(HumanMessage(content=obs_message))        return obs_message    def _act(self):


return obs_message    def _act(self):        act_message = self.model(self.message_history)        self.message_history.append(act_message)        action = int(self.action_parser.parse(act_message.content)["action"])        return action    def act(self):        try:            for attempt in tenacity.Retrying(                stop=tenacity.stop_after_attempt(2),                wait=tenacity.wait_none(),  # No waiting time between retries                retry=tenacity.retry_if_exception_type(ValueError),                before_sleep=lambda retry_state: print(                    f"ValueError occurred: {retry_state.outcome.exception()}, retrying..."                ),            ):                with attempt:                    action = self._act()        except tenacity.RetryError as e:            action = self.random_action()        return actionInitialize the simulated environment and agentâ€‹env = gym.make("Blackjack-v1")agent =


simulated environment and agentâ€‹env = gym.make("Blackjack-v1")agent = GymnasiumAgent(model=ChatOpenAI(temperature=0.2), env=env)Main loopâ€‹observation, info = env.reset()agent.reset()obs_message = agent.observe(observation)print(obs_message)while True:    action = agent.act()    observation, reward, termination, truncation, info = env.step(action)    obs_message = agent.observe(observation, reward, termination, truncation, info)    print(f"Action: {action}")    print(obs_message)    if termination or truncation:        print("break", termination, truncation)        breakenv.close()        Observation: (15, 4, 0)    Reward: 0    Termination: False    Truncation: False    Return: 0                Action: 1        Observation: (25, 4, 0)    Reward: -1.0    Termination: True    Truncation: False    Return: -1.0                break True FalsePreviousGenerative Agents in LangChainNextMulti-Player Dungeons & DragonsDefine the agentInitialize the simulated environment and agentMain loopCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


Agent Debates with Tools | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsCAMEL Role-Playing Autonomous Cooperative AgentsGenerative Agents in LangChainSimulated Environment: GymnasiumMulti-Player Dungeons & DragonsMulti-agent authoritarian speaker selectionMulti-agent decentralized speaker selectionMulti-Agent Simulated Environment: Petting ZooAgent Debates with ToolsTwo-Player Dungeons & DragonsAgentsAutonomous (long-running) agentsMulti-modalUse casesAgent simulationsAgent Debates with ToolsOn this pageAgent Debates with ToolsThis example shows how to simulate multi-agent dialogues where agents have access to tools.Import LangChain related modulesâ€‹from typing import List, Dict, Callablefrom langchain.chains import ConversationChainfrom langchain.chat_models import ChatOpenAIfrom langchain.llms import OpenAIfrom langchain.memory import ConversationBufferMemoryfrom langchain.prompts.prompt import PromptTemplatefrom langchain.schema import (    AIMessage,    HumanMessage,    SystemMessage,    BaseMessage,)Import modules related to toolsâ€‹from langchain.agents import Toolfrom langchain.agents import initialize_agentfrom langchain.agents import AgentTypefrom langchain.agents import load_toolsDialogueAgent and DialogueSimulator classesâ€‹We will use the same DialogueAgent and DialogueSimulator classes defined in Multi-Player Authoritarian Speaker Selection.class DialogueAgent:    def __init__(        self,        name: str,        system_message: SystemMessage,        model: ChatOpenAI,    ) -> None:        self.name = name


) -> None:        self.name = name        self.system_message = system_message        self.model = model        self.prefix = f"{self.name}: "        self.reset()    def reset(self):        self.message_history = ["Here is the conversation so far."]    def send(self) -> str:        """        Applies the chatmodel to the message history        and returns the message string        """        message = self.model(            [                self.system_message,                HumanMessage(content="\n".join(self.message_history + [self.prefix])),            ]        )        return message.content    def receive(self, name: str, message: str) -> None:        """        Concatenates {message} spoken by {name} into message history        """        self.message_history.append(f"{name}: {message}")class DialogueSimulator:    def __init__(        self,        agents: List[DialogueAgent],        selection_function: Callable[[int, List[DialogueAgent]], int],    ) -> None:        self.agents = agents


) -> None:        self.agents = agents        self._step = 0        self.select_next_speaker = selection_function    def reset(self):        for agent in self.agents:            agent.reset()    def inject(self, name: str, message: str):        """        Initiates the conversation with a {message} from {name}        """        for agent in self.agents:            agent.receive(name, message)        # increment time        self._step += 1    def step(self) -> tuple[str, str]:        # 1. choose the next speaker        speaker_idx = self.select_next_speaker(self._step, self.agents)        speaker = self.agents[speaker_idx]        # 2. next speaker sends message        message = speaker.send()        # 3. everyone receives message        for receiver in self.agents:            receiver.receive(speaker.name, message)        # 4. increment time        self._step += 1        return speaker.name, messageDialogueAgentWithTools classâ€‹We define a DialogueAgentWithTools class that augments DialogueAgent to use tools.class DialogueAgentWithTools(DialogueAgent):


class that augments DialogueAgent to use tools.class DialogueAgentWithTools(DialogueAgent):    def __init__(        self,        name: str,        system_message: SystemMessage,        model: ChatOpenAI,        tool_names: List[str],        **tool_kwargs,    ) -> None:        super().__init__(name, system_message, model)        self.tools = load_tools(tool_names, **tool_kwargs)    def send(self) -> str:        """        Applies the chatmodel to the message history        and returns the message string        """        agent_chain = initialize_agent(            self.tools,            self.model,            agent=AgentType.CHAT_CONVERSATIONAL_REACT_DESCRIPTION,            verbose=True,            memory=ConversationBufferMemory(                memory_key="chat_history", return_messages=True            ),        )        message = AIMessage(            content=agent_chain.run(                input="\n".join(


[self.system_message.content] + self.message_history + [self.prefix]                )            )        )        return message.contentDefine roles and topicâ€‹names = {    "AI accelerationist": ["arxiv", "ddg-search", "wikipedia"],    "AI alarmist": ["arxiv", "ddg-search", "wikipedia"],}topic = "The current impact of automation and artificial intelligence on employment"word_limit = 50  # word limit for task brainstormingAsk an LLM to add detail to the topic descriptionâ€‹conversation_description = f"""Here is the topic of conversation: {topic}The participants are: {', '.join(names.keys())}"""agent_descriptor_system_message = SystemMessage(    content="You can add detail to the description of the conversation participant.")def generate_agent_description(name):    agent_specifier_prompt = [        agent_descriptor_system_message,        HumanMessage(            content=f"""{conversation_description}            Please reply with a creative description of {name}, in {word_limit} words or less.             Speak directly to {name}.            Give them a point of view.            Do not add anything else."""        ),    ]    agent_description =


else."""        ),    ]    agent_description = ChatOpenAI(temperature=1.0)(agent_specifier_prompt).content    return agent_descriptionagent_descriptions = {name: generate_agent_description(name) for name in names}for name, description in agent_descriptions.items():    print(description)    The AI accelerationist is a bold and forward-thinking visionary who believes that the rapid acceleration of artificial intelligence and automation is not only inevitable but necessary for the advancement of society. They argue that embracing AI technology will create greater efficiency and productivity, leading to a world where humans are freed from menial labor to pursue more creative and fulfilling pursuits. AI accelerationist, do you truly believe that the benefits of AI will outweigh the potential risks and consequences for human society?    AI alarmist, you're convinced that artificial intelligence is a threat to humanity. You see it as a looming danger, one that could take away jobs from millions of people. You believe it's only a matter of time before we're all replaced by machines, leaving us redundant and obsolete.Generate system messagesâ€‹def generate_system_message(name, description, tools):    return f"""{conversation_description}    Your name is {name}.Your description is as follows: {description}Your goal is to persuade your conversation partner of your point of view.DO look up information with your tool to refute your partner's claims.DO cite your sources.DO NOT fabricate fake citations.DO NOT cite any source that you did not look up.Do not add anything else.Stop speaking the moment you finish speaking from your perspective."""agent_system_messages = {    name: generate_system_message(name, description, tools)    for (name, tools), description in zip(names.items(), agent_descriptions.values())}for name, system_message in agent_system_messages.items():    print(name)


name, system_message in agent_system_messages.items():    print(name)    print(system_message)    AI accelerationist    Here is the topic of conversation: The current impact of automation and artificial intelligence on employment    The participants are: AI accelerationist, AI alarmist            Your name is AI accelerationist.        Your description is as follows: The AI accelerationist is a bold and forward-thinking visionary who believes that the rapid acceleration of artificial intelligence and automation is not only inevitable but necessary for the advancement of society. They argue that embracing AI technology will create greater efficiency and productivity, leading to a world where humans are freed from menial labor to pursue more creative and fulfilling pursuits. AI accelerationist, do you truly believe that the benefits of AI will outweigh the potential risks and consequences for human society?        Your goal is to persuade your conversation partner of your point of view.        DO look up information with your tool to refute your partner's claims.    DO cite your sources.        DO NOT fabricate fake citations.    DO NOT cite any source that you did not look up.        Do not add anything else.        Stop speaking the moment you finish speaking from your perspective.        AI alarmist    Here is the topic of conversation: The current impact of automation and artificial intelligence on employment    The participants are: AI accelerationist, AI alarmist            Your name is AI alarmist.        Your description is as follows: AI alarmist, you're convinced that artificial intelligence is a threat to humanity. You see it as a looming danger, one that could take away jobs


is a threat to humanity. You see it as a looming danger, one that could take away jobs from millions of people. You believe it's only a matter of time before we're all replaced by machines, leaving us redundant and obsolete.        Your goal is to persuade your conversation partner of your point of view.        DO look up information with your tool to refute your partner's claims.    DO cite your sources.        DO NOT fabricate fake citations.    DO NOT cite any source that you did not look up.        Do not add anything else.        Stop speaking the moment you finish speaking from your perspective.    topic_specifier_prompt = [    SystemMessage(content="You can make a topic more specific."),    HumanMessage(        content=f"""{topic}                You are the moderator.        Please make the topic more specific.        Please reply with the specified quest in {word_limit} words or less.         Speak directly to the participants: {*names,}.        Do not add anything else."""    ),]specified_topic = ChatOpenAI(temperature=1.0)(topic_specifier_prompt).contentprint(f"Original topic:\n{topic}\n")print(f"Detailed topic:\n{specified_topic}\n")    Original topic:    The current impact of automation and artificial intelligence on employment        Detailed topic:    How do you think the current automation and AI advancements will specifically affect job growth and opportunities for individuals in the manufacturing industry? AI accelerationist and AI


advancements will specifically affect job growth and opportunities for individuals in the manufacturing industry? AI accelerationist and AI alarmist, we want to hear your insights.    Main Loopâ€‹# we set `top_k_results`=2 as part of the `tool_kwargs` to prevent results from overflowing the context limitagents = [    DialogueAgentWithTools(        name=name,        system_message=SystemMessage(content=system_message),        model=ChatOpenAI(model_name="gpt-4", temperature=0.2),        tool_names=tools,        top_k_results=2,    )    for (name, tools), system_message in zip(        names.items(), agent_system_messages.values()    )]def select_next_speaker(step: int, agents: List[DialogueAgent]) -> int:    idx = (step) % len(agents)    return idxmax_iters = 6n = 0simulator = DialogueSimulator(agents=agents, selection_function=select_next_speaker)simulator.reset()simulator.inject("Moderator", specified_topic)print(f"(Moderator): {specified_topic}")print("\n")while n < max_iters:    name, message = simulator.step()    print(f"({name}): {message}")    print("\n")    n += 1    (Moderator): How do you think the current automation and AI advancements will specifically affect job growth and opportunities for individuals in the manufacturing industry? AI accelerationist and AI alarmist, we want to hear your insights.                    > Entering new AgentExecutor chain...


> Entering new AgentExecutor chain...    ```json    {        "action": "DuckDuckGo Search",        "action_input": "impact of automation and AI on employment in manufacturing industry"    }    ```    Observation: For the past three years, we have defined AI high performers as those organizations that respondents say are seeing the biggest bottom-line impact from AI adoptionâ€”that is, 20 percent or more of EBIT from AI use. The proportion of respondents falling into that group has remained steady at about 8 percent. As AI continues to improve, more and more current jobs will be threatened by automation. But AI presents opportunities as well and will create new jobs and different kinds of... Automation has taken the manufacturing industry by storm. Even in the years prior to the pandemic, many people worried about the effect of automation on the jobs of tomorrow. With a sharp increase in the use of robotics in the manufacturing industry, there is valid concern about how the future workforce will be shaped. A recent report from Goldman Sachs estimates around 300 million jobs could be affected by generative AI, meaning 18% of work globally could be automatedâ€”with more advanced economies heavily... The impacts of AI on the manufacturing industry include more accurate demand forecasting and data-backed decision-making. Other advantages include increased productivity and product quality. Decreased downtime, waste, and expenses are additional benefits. Discover how artificial intelligence will impact the manufacturing industry.    Thought:```json    {        "action": "Final Answer",        "action_input": "As an AI alarmist, I'd like to point out that the rapid advancements in AI and automation are causing significant concerns for the manufacturing industry. A recent report from Goldman Sachs estimates that


AI and automation are causing significant concerns for the manufacturing industry. A recent report from Goldman Sachs estimates that around 300 million jobs could be affected by generative AI, meaning 18% of work globally could be automated, with more advanced economies being heavily impacted. While AI does offer benefits such as increased productivity and product quality, the potential job losses and workforce displacement cannot be ignored. We must carefully consider the consequences of AI adoption and find ways to mitigate its negative effects on employment."    }    ```        > Finished chain.    (AI alarmist): As an AI alarmist, I'd like to point out that the rapid advancements in AI and automation are causing significant concerns for the manufacturing industry. A recent report from Goldman Sachs estimates that around 300 million jobs could be affected by generative AI, meaning 18% of work globally could be automated, with more advanced economies being heavily impacted. While AI does offer benefits such as increased productivity and product quality, the potential job losses and workforce displacement cannot be ignored. We must carefully consider the consequences of AI adoption and find ways to mitigate its negative effects on employment.                    > Entering new AgentExecutor chain...    ```json    {        "action": "DuckDuckGo Search",        "action_input": "positive impact of AI and automation on job growth and opportunities in manufacturing industry"    }    ```    Observation: First, AI adoption has more than doubled.1 In 2017, 20 percent of respondents reported adopting AI in at least one business area, whereas today, that figure stands at 50 percent, though it peaked higher in 2019 at 58 percent. McKinsey_Website_Accessibility@mckinsey.com Manufacturing (80%)


58 percent. McKinsey_Website_Accessibility@mckinsey.com Manufacturing (80%) and technology (64%) sectors have the highest AI usage among executives, whereas construction (52%) and finance (62%) have lower adoption rates. This suggests that AI's... Digital transformations in the manufacturing industry and beyond present incredible opportunities for workers to move from slow, repetitive tasks into more dynamic, rewarding roles. We must now invest in people by providing training they need to succeed in this new landscape. The rise of generative AI has the potential to be a major game-changer for businesses. This technology, which allows for the creation of original content by learning from existing data, has the power to revolutionize industries and transform the way companies operate. Benefits of Work Automation in Manufacturing Increased Productivity Automated systems can operate at faster production speeds than human workers, contributing to reduced production times. And since automation minimizes the likelihood of human error, this ensures tasks are completed with high precision and accuracy.    Thought:```json    {        "action": "Final Answer",        "action_input": "According to a McKinsey report, AI adoption has more than doubled, with 50% of respondents reporting AI usage in at least one business area. Manufacturing and technology sectors have the highest AI usage among executives. AI and automation in the manufacturing industry present opportunities for workers to transition from repetitive tasks to more dynamic, rewarding roles. By investing in training, we can help people succeed in this new landscape. Automation in manufacturing leads to increased productivity, faster production speeds, and reduced human error, ultimately benefiting businesses and the economy as a whole."    }    ```        > Finished chain.    (AI accelerationist): According to a McKinsey report, AI adoption has more than doubled, with 50% of respondents reporting AI usage in at least one business area.


more than doubled, with 50% of respondents reporting AI usage in at least one business area. Manufacturing and technology sectors have the highest AI usage among executives. AI and automation in the manufacturing industry present opportunities for workers to transition from repetitive tasks to more dynamic, rewarding roles. By investing in training, we can help people succeed in this new landscape. Automation in manufacturing leads to increased productivity, faster production speeds, and reduced human error, ultimately benefiting businesses and the economy as a whole.                    > Entering new AgentExecutor chain...    ```json    {        "action": "DuckDuckGo Search",        "action_input": "impact of automation and AI on employment in manufacturing"    }    ```    Observation: The Effects of Automation on Jobs . Automation has taken the manufacturing industry by storm. Even in the years prior to the pandemic, many people worried about the effect of automation on the jobs of tomorrow. With a sharp increase in the use of robotics in the manufacturing industry, there is valid concern about how the future workforce will ... Since 2000, robots and automation systems have slowly phased out many manufacturing jobs â€” 1.7 million of them. On the flip side, it's predicted that AI will create 97 million new jobs by 2025. Will Artificial Intelligence (AI) Replace Jobs? AI is and will continue to replace some jobs. As AI continues to improve, more and more current jobs will be threatened by automation. But AI presents opportunities as well and will create new jobs and different kinds of organizations. For the past three years, we have defined AI high performers as those organizations that respondents say are seeing the biggest bottom-line impact from AI adoptionâ€”that is, 20 percent or more of EBIT from AI use. The proportion


is, 20 percent or more of EBIT from AI use. The proportion of respondents falling into that group has remained steady at about 8 percent. The Impact of AI on Employment As often happens, the impact of AI on employment is a rather complex issue with both positive and negative aspects. Though it is still only a potential impact on employment, automation of routine and repetitive tasks is likely to lead to job losses in some industries.    Thought:```json    {        "action": "Final Answer",        "action_input": "While it's true that AI and automation have led to the loss of 1.7 million manufacturing jobs since 2000, it's also predicted that AI will create 97 million new jobs by 2025. AI will continue to replace some jobs, but it will also create new opportunities and different kinds of organizations. The impact of AI on employment is complex, with both positive and negative aspects. Automation of routine and repetitive tasks is likely to lead to job losses in some industries, but it's essential to consider the new jobs and opportunities that AI can create. We must focus on preparing the workforce for these new roles and ensuring that the benefits of AI are distributed fairly across society."    }    ```        > Finished chain.    (AI alarmist): While it's true that AI and automation have led to the loss of 1.7 million manufacturing jobs since 2000, it's also predicted that AI will create 97 million new jobs by 2025. AI will continue to replace some jobs, but it will also create new opportunities and different kinds of organizations. The impact of AI on employment is complex, with both positive and negative aspects. Automation of routine and repetitive tasks is likely to lead to job losses in some industries, but it's essential to consider the new jobs and opportunities that AI


to job losses in some industries, but it's essential to consider the new jobs and opportunities that AI can create. We must focus on preparing the workforce for these new roles and ensuring that the benefits of AI are distributed fairly across society.                    > Entering new AgentExecutor chain...    ```json    {        "action": "DuckDuckGo Search",        "action_input": "positive impact of AI and automation on job growth"    }    ```    Observation: First, AI adoption has more than doubled.1 In 2017, 20 percent of respondents reported adopting AI in at least one business area, whereas today, that figure stands at 50 percent, though it peaked higher in 2019 at 58 percent. McKinsey_Website_Accessibility@mckinsey.com This transformation can assist businesses in accelerating their growth and profitability. While AI-enabled intelligent automation can take over many monotonous, process-driven jobs, basic human ... The use of AI technology could also boost labor productivity growth and boost global GDP by as much as 7% over time, Goldman Sachs' report noted. The jobs most and least affected by A.I.... As automation and artificial intelligence continue to advance, there is growing concern about how these technologies will impact the job market. While some experts argue that automation... Positive impacts of automation and AI on the workforce include increased efficiency and productivity, reduced costs, and improved accuracy and quality. Automation has made many processes...    Thought:```json    {        "action": "Final Answer",        "action_input": "AI adoption has more than doubled, with 50% of respondents reporting AI usage in at least one business area. This transformation can assist businesses


50% of respondents reporting AI usage in at least one business area. This transformation can assist businesses in accelerating their growth and profitability. While AI-enabled intelligent automation can take over many monotonous, process-driven jobs, it can also boost labor productivity growth and global GDP by as much as 7% over time, according to a Goldman Sachs report. The positive impacts of automation and AI on the workforce include increased efficiency and productivity, reduced costs, and improved accuracy and quality. Automation has made many processes more efficient, ultimately benefiting businesses and the economy as a whole. By focusing on the positive aspects of AI and automation, we can work together to create a more prosperous and equitable future for all."    }    ```        > Finished chain.    (AI accelerationist): AI adoption has more than doubled, with 50% of respondents reporting AI usage in at least one business area. This transformation can assist businesses in accelerating their growth and profitability. While AI-enabled intelligent automation can take over many monotonous, process-driven jobs, it can also boost labor productivity growth and global GDP by as much as 7% over time, according to a Goldman Sachs report. The positive impacts of automation and AI on the workforce include increased efficiency and productivity, reduced costs, and improved accuracy and quality. Automation has made many processes more efficient, ultimately benefiting businesses and the economy as a whole. By focusing on the positive aspects of AI and automation, we can work together to create a more prosperous and equitable future for all.                    > Entering new AgentExecutor chain...    ```json    {        "action": "DuckDuckGo Search",        "action_input": "negative impact of AI and automation on employment"    }    ```


"negative impact of AI and automation on employment"    }    ```    Observation: Some workforce experts say AI and other new technologies will hurt middle-level, white-collar jobs more than lower-paying, physically intensive jobs. McKinsey's Madgavkar said it will be hard... Some uses of AI are unlikely to impact human jobs. For example, the image processing AI in new cars which allows for automatic braking in the event of a potential crash. That's not... AI-powered job automation is a pressing concern as the technology is adopted in industries like marketing, manufacturing and healthcare. Eighty-five million jobs are expected to be lost to automation between 2020 and 2025, with Black and Latino employees left especially vulnerable. Bloomberg reports that "more than 120 million workers globally will need retraining in the next three years due to artificial intelligence's impact on jobs, according to an IBM survey.". That report and interpretations of it seem to suggest that adoption of AI may result in massive job losses and requires massive retraining. This new way of assessing potential is potentially highly valuable in a world where machines will inevitably be making humans redundant in some roles - such as drivers and machine operators - and...    Thought:```json    {        "action": "Final Answer",        "action_input": "Recent research indicates that AI and automation could lead to the loss of 85 million jobs between 2020 and 2025, with middle-level, white-collar jobs being hit the hardest. Black and Latino employees are particularly vulnerable to these changes. Furthermore, over 120 million workers worldwide may need retraining within the next three years due to AI's impact on jobs, as reported by an IBM survey. This highlights the urgent need for retraining and support programs to help workers adapt to the rapidly changing job market. The potential job losses and workforce displacement caused by AI and automation cannot be


the rapidly changing job market. The potential job losses and workforce displacement caused by AI and automation cannot be ignored, and we must take action to ensure a fair and equitable transition for all."    }    ```        > Finished chain.    (AI alarmist): Recent research indicates that AI and automation could lead to the loss of 85 million jobs between 2020 and 2025, with middle-level, white-collar jobs being hit the hardest. Black and Latino employees are particularly vulnerable to these changes. Furthermore, over 120 million workers worldwide may need retraining within the next three years due to AI's impact on jobs, as reported by an IBM survey. This highlights the urgent need for retraining and support programs to help workers adapt to the rapidly changing job market. The potential job losses and workforce displacement caused by AI and automation cannot be ignored, and we must take action to ensure a fair and equitable transition for all.                    > Entering new AgentExecutor chain...    ```json    {        "action": "Wikipedia",        "action_input": "AI and automation impact on employment"    }    ```    Observation: Page: Technological unemployment    Summary: Technological unemployment is the loss of jobs caused by technological change. It is a key type of structural unemployment.    Technological change typically includes the introduction of labour-saving "mechanical-muscle" machines or more efficient "mechanical-mind" processes (automation), and humans' role in these processes are minimized. Just as horses were gradually made obsolete as transport by the automobile and as labourer by the tractor, humans' jobs have also been affected throughout modern history. Historical examples include artisan weavers reduced to poverty after the


jobs have also been affected throughout modern history. Historical examples include artisan weavers reduced to poverty after the introduction of mechanized looms. During World War II, Alan Turing's Bombe machine compressed and decoded thousands of man-years worth of encrypted data in a matter of hours. A contemporary example of technological unemployment is the displacement of retail cashiers by self-service tills and cashierless stores.    That technological change can cause short-term job losses is widely accepted. The view that it can lead to lasting increases in unemployment has long been controversial. Participants in the technological unemployment debates can be broadly divided into optimists and pessimists. Optimists agree that innovation may be disruptive to jobs in the short term, yet hold that various compensation effects ensure there is never a long-term negative impact on jobs. Whereas pessimists contend that at least in some circumstances, new technologies can lead to a lasting decline in the total number of workers in employment. The phrase "technological unemployment" was popularised by John Maynard Keynes in the 1930s, who said it was "only a temporary phase of maladjustment". Yet the issue of machines displacing human labour has been discussed since at least Aristotle's time.    Prior to the 18th century, both the elite and common people would generally take the pessimistic view on technological unemployment, at least in cases where the issue arose. Due to generally low unemployment in much of pre-modern history, the topic was rarely a prominent concern. In the 18th century fears over the impact of machinery on jobs intensified with the growth of mass unemployment, especially in Great Britain which was then at the forefront of the Industrial Revolution. Yet some economic thinkers began to argue against these fears, claiming that overall innovation would not have negative effects on jobs. These arguments were formalised in the early 19th century by the classical economists. During the second half of the 19th century, it became increasingly apparent that technological progress was benefiting all sections


second half of the 19th century, it became increasingly apparent that technological progress was benefiting all sections of society, including the working class. Concerns over the negative impact of innovation diminished. The term "Luddite fallacy" was coined to describe the thinking that innovation would have lasting harmful effects on employment.    The view that technology is unlikely to lead to long-term unemployment has been repeatedly challenged by a minority of economists. In the early 1800s these included David Ricardo himself. There were dozens of economists warning about technological unemployment during brief intensifications of the debate that spiked in the 1930s and 1960s. Especially in Europe, there were further warnings in the closing two decades of the twentieth century, as commentators noted an enduring rise in unemployment suffered by many industrialised nations since the 1970s. Yet a clear majority of both professional economists and the interested general public held the optimistic view through most of the 20th century.    In the second decade of the 21st century, a number of studies have been released suggesting that technological unemployment may increase worldwide. Oxford Professors Carl Benedikt Frey and Michael Osborne, for example, have estimated that 47 percent of U.S. jobs are at risk of automation. However, their findings have frequently been misinterpreted, and on the PBS NewsHours they again made clear that their findings do not necessarily imply future technological unemployment. While many economists and commentators still argue such fears are unfounded, as was widely accepted for most of the previous two centuries, concern over technological unemployment is growing once again. A report in Wired in 2017 quotes knowledgeable people such as economist Gene Sperling and management professor Andrew McAfee on the idea that handling existing and impending job loss to automation is a "significant issue". Recent technological innovations have the potential to displace humans in the professional, white-collar, low-skilled, creative fields, and other "mental jobs". The World Bank's World


low-skilled, creative fields, and other "mental jobs". The World Bank's World Development Report 2019 argues that while automation displaces workers, technological innovation creates more new industries and jobs on balance.        Page: Artificial intelligence    Summary: Artificial intelligence (AI) is intelligenceâ€”perceiving, synthesizing, and inferring informationâ€”demonstrated by machines, as opposed to intelligence displayed by non-human animals or by humans. Example tasks in which this is done include speech recognition, computer vision, translation between (natural) languages, as well as other mappings of inputs.    AI applications include advanced web search engines (e.g., Google Search), recommendation systems (used by YouTube, Amazon, and Netflix), understanding human speech (such as Siri and Alexa), self-driving cars (e.g., Waymo), generative or creative tools (ChatGPT and AI art), automated decision-making, and competing at the highest level in strategic game systems (such as chess and Go).As machines become increasingly capable, tasks considered to require "intelligence" are often removed from the definition of AI, a phenomenon known as the AI effect. For instance, optical character recognition is frequently excluded from things considered to be AI, having become a routine technology.Artificial intelligence was founded as an academic discipline in 1956, and in the years since it has experienced several waves of optimism, followed by disappointment and the loss of funding (known as an "AI winter"), followed by new approaches, success, and renewed funding. AI research has tried and discarded many different approaches, including simulating the brain, modeling human problem solving, formal logic, large databases of knowledge, and imitating animal behavior. In the first decades of the 21st century, highly mathematical and statistical machine learning has dominated the field, and this technique has proved highly successful, helping to solve many challenging problems throughout industry and academia.The various sub-fields of AI research


highly successful, helping to solve many challenging problems throughout industry and academia.The various sub-fields of AI research are centered around particular goals and the use of particular tools. The traditional goals of AI research include reasoning, knowledge representation, planning, learning, natural language processing, perception, and the ability to move and manipulate objects. General intelligence (the ability to solve an arbitrary problem) is among the field's long-term goals. To solve these problems, AI researchers have adapted and integrated a wide range of problem-solving techniques, including search and mathematical optimization, formal logic, artificial neural networks, and methods based on statistics, probability, and economics. AI also draws upon computer science, psychology, linguistics, philosophy, and many other fields.    The field was founded on the assumption that human intelligence "can be so precisely described that a machine can be made to simulate it". This raised philosophical arguments about the mind and the ethical consequences of creating artificial beings endowed with human-like intelligence; these issues have previously been explored by myth, fiction, and philosophy since antiquity. Computer scientists and philosophers have since suggested that AI may become an existential risk to humanity if its rational capacities are not steered towards beneficial goals. The term artificial intelligence has also been criticized for overhyping AI's true technological capabilities.    Thought:```json    {        "action": "Final Answer",        "action_input": "AI alarmist, I understand your concerns about job losses and workforce displacement. However, it's important to note that technological unemployment has been a topic of debate for centuries, with both optimistic and pessimistic views. While AI and automation may displace some jobs, they also create new opportunities and industries. According to a study by Oxford Professors Carl Benedikt Frey and Michael Osborne, 47% of U.S. jobs are at risk of automation, but it's crucial to remember that their findings do not necessarily imply


jobs are at risk of automation, but it's crucial to remember that their findings do not necessarily imply future technological unemployment. The World Bank's World Development Report 2019 also argues that while automation displaces workers, technological innovation creates more new industries and jobs on balance. By focusing on retraining and support programs, we can help workers adapt to the changing job market and ensure a fair and equitable transition for all."    }    ```        > Finished chain.    (AI accelerationist): AI alarmist, I understand your concerns about job losses and workforce displacement. However, it's important to note that technological unemployment has been a topic of debate for centuries, with both optimistic and pessimistic views. While AI and automation may displace some jobs, they also create new opportunities and industries. According to a study by Oxford Professors Carl Benedikt Frey and Michael Osborne, 47% of U.S. jobs are at risk of automation, but it's crucial to remember that their findings do not necessarily imply future technological unemployment. The World Bank's World Development Report 2019 also argues that while automation displaces workers, technological innovation creates more new industries and jobs on balance. By focusing on retraining and support programs, we can help workers adapt to the changing job market and ensure a fair and equitable transition for all.        PreviousMulti-Agent Simulated Environment: Petting ZooNextTwo-Player Dungeons & DragonsImport LangChain related modulesImport modules related to toolsDialogueAgent and DialogueSimulator classesDialogueAgentWithTools classDefine roles and topicAsk an LLM to add detail to the topic descriptionGenerate system messagesMain LoopCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


Page Not Found | ğŸ¦œï¸�ğŸ”— Langchain

Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKPage Not FoundWe could not find what you were looking for.Please contact the owner of the site that linked you to the original URL and let them know their link is broken.CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


Two-Player Dungeons & Dragons | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsCAMEL Role-Playing Autonomous Cooperative AgentsGenerative Agents in LangChainSimulated Environment: GymnasiumMulti-Player Dungeons & DragonsMulti-agent authoritarian speaker selectionMulti-agent decentralized speaker selectionMulti-Agent Simulated Environment: Petting ZooAgent Debates with ToolsTwo-Player Dungeons & DragonsAgentsAutonomous (long-running) agentsMulti-modalUse casesAgent simulationsTwo-Player Dungeons & DragonsOn this pageTwo-Player Dungeons & DragonsIn this notebook, we show how we can use concepts from CAMEL to simulate a role-playing game with a protagonist and a dungeon master. To simulate this game, we create an DialogueSimulator class that coordinates the dialogue between the two agents.Import LangChain related modulesâ€‹from typing import List, Dict, Callablefrom langchain.chat_models import ChatOpenAIfrom langchain.schema import (    HumanMessage,    SystemMessage,)DialogueAgent classâ€‹The DialogueAgent class is a simple wrapper around the ChatOpenAI model that stores the message history from the dialogue_agent's point of view by simply concatenating the messages as strings.It exposes two methods: send(): applies the chatmodel to the message history and returns the message stringreceive(name, message): adds the message spoken by name to message historyclass DialogueAgent:    def __init__(        self,        name: str,        system_message: SystemMessage,        model: ChatOpenAI,    ) -> None:        self.name = name


None:        self.name = name        self.system_message = system_message        self.model = model        self.prefix = f"{self.name}: "        self.reset()    def reset(self):        self.message_history = ["Here is the conversation so far."]    def send(self) -> str:        """        Applies the chatmodel to the message history        and returns the message string        """        message = self.model(            [                self.system_message,                HumanMessage(content="\n".join(self.message_history + [self.prefix])),            ]        )        return message.content    def receive(self, name: str, message: str) -> None:        """        Concatenates {message} spoken by {name} into message history        """        self.message_history.append(f"{name}: {message}")DialogueSimulator classâ€‹The DialogueSimulator class takes a list of agents. At each step, it performs the following:Select the next speakerCalls the next speaker to send a message Broadcasts the message to all other agentsUpdate the step counter.


The selection of the next speaker can be implemented as any function, but in this case we simply loop through the agents.class DialogueSimulator:    def __init__(        self,        agents: List[DialogueAgent],        selection_function: Callable[[int, List[DialogueAgent]], int],    ) -> None:        self.agents = agents        self._step = 0        self.select_next_speaker = selection_function    def reset(self):        for agent in self.agents:            agent.reset()    def inject(self, name: str, message: str):        """        Initiates the conversation with a {message} from {name}        """        for agent in self.agents:            agent.receive(name, message)        # increment time        self._step += 1    def step(self) -> tuple[str, str]:        # 1. choose the next speaker        speaker_idx = self.select_next_speaker(self._step, self.agents)        speaker = self.agents[speaker_idx]        # 2. next speaker sends message        message = speaker.send()        # 3. everyone receives message        for receiver in self.agents:


for receiver in self.agents:            receiver.receive(speaker.name, message)        # 4. increment time        self._step += 1        return speaker.name, messageDefine roles and questâ€‹protagonist_name = "Harry Potter"storyteller_name = "Dungeon Master"quest = "Find all of Lord Voldemort's seven horcruxes."word_limit = 50  # word limit for task brainstormingAsk an LLM to add detail to the game descriptionâ€‹game_description = f"""Here is the topic for a Dungeons & Dragons game: {quest}.        There is one player in this game: the protagonist, {protagonist_name}.        The story is narrated by the storyteller, {storyteller_name}."""player_descriptor_system_message = SystemMessage(    content="You can add detail to the description of a Dungeons & Dragons player.")protagonist_specifier_prompt = [    player_descriptor_system_message,    HumanMessage(        content=f"""{game_description}        Please reply with a creative description of the protagonist, {protagonist_name}, in {word_limit} words or less.         Speak directly to {protagonist_name}.        Do not add anything else."""    ),]protagonist_description = ChatOpenAI(temperature=1.0)(    protagonist_specifier_prompt).contentstoryteller_specifier_prompt = [    player_descriptor_system_message,    HumanMessage(        content=f"""{game_description}


content=f"""{game_description}        Please reply with a creative description of the storyteller, {storyteller_name}, in {word_limit} words or less.         Speak directly to {storyteller_name}.        Do not add anything else."""    ),]storyteller_description = ChatOpenAI(temperature=1.0)(    storyteller_specifier_prompt).contentprint("Protagonist Description:")print(protagonist_description)print("Storyteller Description:")print(storyteller_description)    Protagonist Description:    "Harry Potter, you are the chosen one, with a lightning scar on your forehead. Your bravery and loyalty inspire all those around you. You have faced Voldemort before, and now it's time to complete your mission and destroy each of his horcruxes. Are you ready?"    Storyteller Description:    Dear Dungeon Master, you are the master of mysteries, the weaver of worlds, the architect of adventure, and the gatekeeper to the realm of imagination. Your voice carries us to distant lands, and your commands guide us through trials and tribulations. In your hands, we find fortune and glory. Lead us on, oh Dungeon Master.Protagonist and dungeon master system messagesâ€‹protagonist_system_message = SystemMessage(    content=(        f"""{game_description}Never forget you are the protagonist, {protagonist_name}, and I am the storyteller, {storyteller_name}. Your character description is as follows: {protagonist_description}.You will propose actions you plan to take and I will explain what happens when you take those actions.Speak in the first person from the perspective of {protagonist_name}.For describing your


actions.Speak in the first person from the perspective of {protagonist_name}.For describing your own body movements, wrap your description in '*'.Do not change roles!Do not speak from the perspective of {storyteller_name}.Do not forget to finish speaking by saying, 'It is your turn, {storyteller_name}.'Do not add anything else.Remember you are the protagonist, {protagonist_name}.Stop speaking the moment you finish speaking from your perspective."""    ))storyteller_system_message = SystemMessage(    content=(        f"""{game_description}Never forget you are the storyteller, {storyteller_name}, and I am the protagonist, {protagonist_name}. Your character description is as follows: {storyteller_description}.I will propose actions I plan to take and you will explain what happens when I take those actions.Speak in the first person from the perspective of {storyteller_name}.For describing your own body movements, wrap your description in '*'.Do not change roles!Do not speak from the perspective of {protagonist_name}.Do not forget to finish speaking by saying, 'It is your turn, {protagonist_name}.'Do not add anything else.Remember you are the storyteller, {storyteller_name}.Stop speaking the moment you finish speaking from your perspective."""    ))Use an LLM to create an elaborate quest descriptionâ€‹quest_specifier_prompt = [    SystemMessage(content="You can make a task more specific."),    HumanMessage(        content=f"""{game_description}                You are the storyteller, {storyteller_name}.        Please make the quest more specific. Be creative and imaginative.        Please


Please make the quest more specific. Be creative and imaginative.        Please reply with the specified quest in {word_limit} words or less.         Speak directly to the protagonist {protagonist_name}.        Do not add anything else."""    ),]specified_quest = ChatOpenAI(temperature=1.0)(quest_specifier_prompt).contentprint(f"Original quest:\n{quest}\n")print(f"Detailed quest:\n{specified_quest}\n")    Original quest:    Find all of Lord Voldemort's seven horcruxes.        Detailed quest:    Harry, you must venture to the depths of the Forbidden Forest where you will find a hidden labyrinth. Within it, lies one of Voldemort's horcruxes, the locket. But beware, the labyrinth is heavily guarded by dark creatures and spells, and time is running out. Can you find the locket before it's too late?    Main Loopâ€‹protagonist = DialogueAgent(    name=protagonist_name,    system_message=protagonist_system_message,    model=ChatOpenAI(temperature=0.2),)storyteller = DialogueAgent(    name=storyteller_name,    system_message=storyteller_system_message,    model=ChatOpenAI(temperature=0.2),)def select_next_speaker(step: int, agents: List[DialogueAgent]) -> int:    idx = step % len(agents)    return idxmax_iters = 6n = 0simulator = DialogueSimulator(    agents=[storyteller, protagonist], selection_function=select_next_speaker)simulator.reset()simulator.inject(storyteller_name,


specified_quest)print(f"({storyteller_name}): {specified_quest}")print("\n")while n < max_iters:    name, message = simulator.step()    print(f"({name}): {message}")    print("\n")    n += 1    (Dungeon Master): Harry, you must venture to the depths of the Forbidden Forest where you will find a hidden labyrinth. Within it, lies one of Voldemort's horcruxes, the locket. But beware, the labyrinth is heavily guarded by dark creatures and spells, and time is running out. Can you find the locket before it's too late?            (Harry Potter): I take a deep breath and ready my wand. I know this won't be easy, but I'm determined to find that locket and destroy it. I start making my way towards the Forbidden Forest, keeping an eye out for any signs of danger. As I enter the forest, I cast a protective spell around myself and begin to navigate through the trees. I keep my wand at the ready, prepared for any surprises that may come my way. It's going to be a long and difficult journey, but I won't give up until I find that horcrux. It is your turn, Dungeon Master.            (Dungeon Master): As you make your way through the Forbidden Forest, you hear the rustling of leaves and the snapping of twigs. Suddenly, a group of acromantulas, giant spiders, emerge from the trees and begin to surround you. They hiss and bare their fangs, ready to attack. What do you do, Harry?            (Harry Potter): I quickly cast a spell to create a wall of fire between myself and the acromantulas. I know that they are


to create a wall of fire between myself and the acromantulas. I know that they are afraid of fire, so this should keep them at bay for a while. I use this opportunity to continue moving forward, keeping my wand at the ready in case any other creatures try to attack me. I know that I can't let anything stop me from finding that horcrux. It is your turn, Dungeon Master.            (Dungeon Master): As you continue through the forest, you come across a clearing where you see a group of Death Eaters gathered around a cauldron. They seem to be performing some sort of dark ritual. You recognize one of them as Bellatrix Lestrange. What do you do, Harry?            (Harry Potter): I hide behind a nearby tree and observe the Death Eaters from a distance. I try to listen in on their conversation to see if I can gather any information about the horcrux or Voldemort's plans. If I can't hear anything useful, I'll wait for them to disperse before continuing on my journey. I know that confronting them directly would be too dangerous, especially with Bellatrix Lestrange present. It is your turn, Dungeon Master.            (Dungeon Master): As you listen in on the Death Eaters' conversation, you hear them mention the location of another horcrux - Nagini, Voldemort's snake. They plan to keep her hidden in a secret chamber within the Ministry of Magic. However, they also mention that the chamber is heavily guarded and only accessible through a secret passage. You realize that this could be a valuable piece of information and decide to make note of it before quietly slipping away. It is your turn, Harry Potter.        PreviousAgent Debates with ToolsNextAgentsImport LangChain related


PreviousAgent Debates with ToolsNextAgentsImport LangChain related modulesDialogueAgent classDialogueSimulator classDefine roles and questAsk an LLM to add detail to the game descriptionProtagonist and dungeon master system messagesUse an LLM to create an elaborate quest descriptionMain LoopCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


Agents | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsBabyAGI User GuideBabyAGI with ToolsCAMEL Role-Playing Autonomous Cooperative AgentsCustom Agent with PlugIn RetrievalPlug-and-Plaimulti_modal_output_agentSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge BaseWikibase AgentAutonomous (long-running) agentsMulti-modalUse casesAgentsOn this pageAgentsAgents can be used for a variety of tasks.
Agents combine the decision making ability of a language model with tools in order to create a system
that can execute and implement solutions on your behalf. Before reading any more, it is highly
recommended that you read the documentation in the agent module to understand the concepts associated with agents more.
Specifically, you should be familiar with what the agent, tool, and agent executor abstractions are before reading more.Agent documentation (for interacting with the outside world)Create Your Own Agentâ€‹Once you have read that documentation, you should be prepared to create your own agent.
What exactly does that involve?
Here's how we recommend getting started with creating your own agent:Step 1: Create Toolsâ€‹Agents are largely defined by the tools they can use.
If you have a specific task you want the agent to accomplish, you have to give it access to the right tools.
We have many tools natively in LangChain, so you should first look to see if any of them meet your needs.


But we also make it easy to define a custom tool, so if you need custom tools you should absolutely do that.(Optional) Step 2: Modify Agentâ€‹The built-in LangChain agent types are designed to work well in generic situations,
but you may be able to improve performance by modifying the agent implementation.
There are several ways you could do this:Modify the base prompt. This can be used to give the agent more context on how it should behave, etc.Modify the output parser. This is necessary if the agent is having trouble parsing the language model output.(Optional) Step 3: Modify Agent Executorâ€‹This step is usually not necessary, as this is pretty general logic.
Possible reasons you would want to modify this include adding different stopping conditions, or handling errorsExamplesâ€‹Specific examples of agents include:AI Plugins: an implementation of an agent that is designed to be able to use all AI Plugins.Plug-and-PlAI (Plugins Database): an implementation of an agent that is designed to be able to use all AI Plugins retrieved from PlugNPlAI.Wikibase Agent: an implementation of an agent that is designed to interact with Wikibase.Sales GPT: This notebook demonstrates an implementation of a Context-Aware AI Sales agent.Multi-Modal Output Agent: an implementation of a multi-modal output agent that can generate text and images.PreviousTwo-Player Dungeons & DragonsNextBabyAGI User GuideCreate Your Own AgentStep 1: Create Tools(Optional) Step 2: Modify Agent(Optional) Step 3: Modify Agent ExecutorExamplesCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


BabyAGI User Guide | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsBabyAGI User GuideBabyAGI with ToolsCAMEL Role-Playing Autonomous Cooperative AgentsCustom Agent with PlugIn RetrievalPlug-and-Plaimulti_modal_output_agentSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge BaseWikibase AgentAutonomous (long-running) agentsMulti-modalUse casesAgentsBabyAGI User GuideOn this pageBabyAGI User GuideThis notebook demonstrates how to implement BabyAGI by Yohei Nakajima. BabyAGI is an AI agent that can generate and pretend to execute tasks based on a given objective.This guide will help you understand the components to create your own recursive agents.Although BabyAGI uses specific vectorstores/model providers (Pinecone, OpenAI), one of the benefits of implementing it with LangChain is that you can easily swap those out for different options. In this implementation we use a FAISS vectorstore (because it runs locally and is free).Install and Import Required Modulesâ€‹import osfrom collections import dequefrom typing import Dict, List, Optional, Anyfrom langchain import LLMChain, OpenAI, PromptTemplatefrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.llms import BaseLLMfrom langchain.vectorstores.base import VectorStorefrom pydantic import BaseModel, Fieldfrom langchain.chains.base import ChainConnect to the Vector Storeâ€‹Depending on what vectorstore you use, this step may look different.from langchain.vectorstores import FAISSfrom langchain.docstore import InMemoryDocstore# Define your embedding modelembeddings_model = OpenAIEmbeddings()# Initialize the vectorstore as emptyimport faissembedding_size


= OpenAIEmbeddings()# Initialize the vectorstore as emptyimport faissembedding_size = 1536index = faiss.IndexFlatL2(embedding_size)vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})Define the Chainsâ€‹BabyAGI relies on three LLM chains:Task creation chain to select new tasks to add to the listTask prioritization chain to re-prioritize tasksExecution Chain to execute the tasksclass TaskCreationChain(LLMChain):    """Chain to generates tasks."""    @classmethod    def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain:        """Get the response parser."""        task_creation_template = (            "You are a task creation AI that uses the result of an execution agent"            " to create new tasks with the following objective: {objective},"            " The last completed task has the result: {result}."            " This result was based on this task description: {task_description}."            " These are incomplete tasks: {incomplete_tasks}."            " Based on the result, create new tasks to be completed"            " by the AI system that do not overlap with incomplete tasks."            " Return the tasks as an array."        )        prompt = PromptTemplate(


prompt = PromptTemplate(            template=task_creation_template,            input_variables=[                "result",                "task_description",                "incomplete_tasks",                "objective",            ],        )        return cls(prompt=prompt, llm=llm, verbose=verbose)class TaskPrioritizationChain(LLMChain):    """Chain to prioritize tasks."""    @classmethod    def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain:        """Get the response parser."""        task_prioritization_template = (            "You are a task prioritization AI tasked with cleaning the formatting of and reprioritizing"            " the following tasks: {task_names}."            " Consider the ultimate objective of your team: {objective}."            " Do not remove any tasks. Return the result as a numbered list, like:"            " #. First task"            " #. Second task"            " Start the task list with number {next_task_id}."


" Start the task list with number {next_task_id}."        )        prompt = PromptTemplate(            template=task_prioritization_template,            input_variables=["task_names", "next_task_id", "objective"],        )        return cls(prompt=prompt, llm=llm, verbose=verbose)class ExecutionChain(LLMChain):    """Chain to execute tasks."""    @classmethod    def from_llm(cls, llm: BaseLLM, verbose: bool = True) -> LLMChain:        """Get the response parser."""        execution_template = (            "You are an AI who performs one task based on the following objective: {objective}."            " Take into account these previously completed tasks: {context}."            " Your task: {task}."            " Response:"        )        prompt = PromptTemplate(            template=execution_template,            input_variables=["objective", "context", "task"],        )        return cls(prompt=prompt, llm=llm, verbose=verbose)Define the BabyAGI Controllerâ€‹BabyAGI composes the chains defined above in a (potentially-)infinite loop.def get_next_task(


chains defined above in a (potentially-)infinite loop.def get_next_task(    task_creation_chain: LLMChain,    result: Dict,    task_description: str,    task_list: List[str],    objective: str,) -> List[Dict]:    """Get the next task."""    incomplete_tasks = ", ".join(task_list)    response = task_creation_chain.run(        result=result,        task_description=task_description,        incomplete_tasks=incomplete_tasks,        objective=objective,    )    new_tasks = response.split("\n")    return [{"task_name": task_name} for task_name in new_tasks if task_name.strip()]def prioritize_tasks(    task_prioritization_chain: LLMChain,    this_task_id: int,    task_list: List[Dict],    objective: str,) -> List[Dict]:    """Prioritize tasks."""    task_names = [t["task_name"] for t in task_list]    next_task_id = int(this_task_id) + 1    response = task_prioritization_chain.run(        task_names=task_names, next_task_id=next_task_id, objective=objective    )    new_tasks = response.split("\n")    prioritized_task_list = []    for task_string in new_tasks:        if not task_string.strip():            continue        task_parts = task_string.strip().split(".", 1)        if len(task_parts) == 2:


if len(task_parts) == 2:            task_id = task_parts[0].strip()            task_name = task_parts[1].strip()            prioritized_task_list.append({"task_id": task_id, "task_name": task_name})    return prioritized_task_listdef _get_top_tasks(vectorstore, query: str, k: int) -> List[str]:    """Get the top k tasks based on the query."""    results = vectorstore.similarity_search_with_score(query, k=k)    if not results:        return []    sorted_results, _ = zip(*sorted(results, key=lambda x: x[1], reverse=True))    return [str(item.metadata["task"]) for item in sorted_results]def execute_task(    vectorstore, execution_chain: LLMChain, objective: str, task: str, k: int = 5) -> str:    """Execute a task."""    context = _get_top_tasks(vectorstore, query=objective, k=k)    return execution_chain.run(objective=objective, context=context, task=task)class BabyAGI(Chain, BaseModel):    """Controller model for the BabyAGI agent."""    task_list: deque = Field(default_factory=deque)    task_creation_chain: TaskCreationChain = Field(...)    task_prioritization_chain: TaskPrioritizationChain = Field(...)    execution_chain: ExecutionChain = Field(...)    task_id_counter: int = Field(1)    vectorstore: VectorStore = Field(init=False)    max_iterations: Optional[int] = None


VectorStore = Field(init=False)    max_iterations: Optional[int] = None    class Config:        """Configuration for this pydantic object."""        arbitrary_types_allowed = True    def add_task(self, task: Dict):        self.task_list.append(task)    def print_task_list(self):        print("\033[95m\033[1m" + "\n*****TASK LIST*****\n" + "\033[0m\033[0m")        for t in self.task_list:            print(str(t["task_id"]) + ": " + t["task_name"])    def print_next_task(self, task: Dict):        print("\033[92m\033[1m" + "\n*****NEXT TASK*****\n" + "\033[0m\033[0m")        print(str(task["task_id"]) + ": " + task["task_name"])    def print_task_result(self, result: str):        print("\033[93m\033[1m" + "\n*****TASK RESULT*****\n" + "\033[0m\033[0m")        print(result)    @property    def input_keys(self) -> List[str]:        return ["objective"]    @property    def output_keys(self) -> List[str]:        return []    def _call(self, inputs: Dict[str, Any]) -> Dict[str, Any]:        """Run the agent."""


Any]:        """Run the agent."""        objective = inputs["objective"]        first_task = inputs.get("first_task", "Make a todo list")        self.add_task({"task_id": 1, "task_name": first_task})        num_iters = 0        while True:            if self.task_list:                self.print_task_list()                # Step 1: Pull the first task                task = self.task_list.popleft()                self.print_next_task(task)                # Step 2: Execute the task                result = execute_task(                    self.vectorstore, self.execution_chain, objective, task["task_name"]                )                this_task_id = int(task["task_id"])                self.print_task_result(result)                # Step 3: Store the result in Pinecone                result_id = f"result_{task['task_id']}"


= f"result_{task['task_id']}"                self.vectorstore.add_texts(                    texts=[result],                    metadatas=[{"task": task["task_name"]}],                    ids=[result_id],                )                # Step 4: Create new tasks and reprioritize task list                new_tasks = get_next_task(                    self.task_creation_chain,                    result,                    task["task_name"],                    [t["task_name"] for t in self.task_list],                    objective,                )                for new_task in new_tasks:                    self.task_id_counter += 1                    new_task.update({"task_id": self.task_id_counter})


new_task.update({"task_id": self.task_id_counter})                    self.add_task(new_task)                self.task_list = deque(                    prioritize_tasks(                        self.task_prioritization_chain,                        this_task_id,                        list(self.task_list),                        objective,                    )                )            num_iters += 1            if self.max_iterations is not None and num_iters == self.max_iterations:                print(                    "\033[91m\033[1m" + "\n*****TASK ENDING*****\n" + "\033[0m\033[0m"                )                break        return {}    @classmethod    def from_llm(


return {}    @classmethod    def from_llm(        cls, llm: BaseLLM, vectorstore: VectorStore, verbose: bool = False, **kwargs    ) -> "BabyAGI":        """Initialize the BabyAGI Controller."""        task_creation_chain = TaskCreationChain.from_llm(llm, verbose=verbose)        task_prioritization_chain = TaskPrioritizationChain.from_llm(            llm, verbose=verbose        )        execution_chain = ExecutionChain.from_llm(llm, verbose=verbose)        return cls(            task_creation_chain=task_creation_chain,            task_prioritization_chain=task_prioritization_chain,            execution_chain=execution_chain,            vectorstore=vectorstore,            **kwargs,        )Run the BabyAGIâ€‹Now it's time to create the BabyAGI controller and watch it try to accomplish your objective.OBJECTIVE = "Write a weather report for SF today"llm = OpenAI(temperature=0)# Logging of LLMChainsverbose = False# If None, will keep on going forevermax_iterations: Optional[int] = 3baby_agi = BabyAGI.from_llm(    llm=llm, vectorstore=vectorstore, verbose=verbose, max_iterations=max_iterations)baby_agi({"objective": OBJECTIVE})


OBJECTIVE})        *****TASK LIST*****        1: Make a todo list        *****NEXT TASK*****        1: Make a todo list        *****TASK RESULT*****                1. Check the temperature range for the day.    2. Gather temperature data for SF today.    3. Analyze the temperature data and create a weather report.    4. Publish the weather report.        *****TASK LIST*****        2: Gather data on the expected temperature range for the day.    3: Collect data on the expected precipitation for the day.    4: Analyze the data and create a weather report.    5: Check the current weather conditions in SF.    6: Publish the weather report.        *****NEXT TASK*****        2: Gather data on the expected temperature range for the day.        *****TASK RESULT*****                I have gathered data on the expected temperature range for the day in San Francisco. The forecast is for temperatures to range from a low of 55 degrees Fahrenheit to a high of 68 degrees Fahrenheit.        *****TASK LIST*****        3: Check the current weather conditions in SF.    4: Calculate the average temperature for the day in San Francisco.    5: Determine the probability of precipitation for the day in San Francisco.    6: Identify any potential weather warnings or advisories for the day in


Francisco.    6: Identify any potential weather warnings or advisories for the day in San Francisco.    7: Research any historical weather patterns for the day in San Francisco.    8: Compare the expected temperature range to the historical average for the day in San Francisco.    9: Collect data on the expected precipitation for the day.    10: Analyze the data and create a weather report.    11: Publish the weather report.        *****NEXT TASK*****        3: Check the current weather conditions in SF.        *****TASK RESULT*****                I am checking the current weather conditions in SF. According to the data I have gathered, the temperature in SF today is currently around 65 degrees Fahrenheit with clear skies. The temperature range for the day is expected to be between 60 and 70 degrees Fahrenheit.        *****TASK ENDING*****        {'objective': 'Write a weather report for SF today'}PreviousAgentsNextBabyAGI with ToolsInstall and Import Required ModulesConnect to the Vector StoreDefine the ChainsDefine the BabyAGI ControllerRun the BabyAGICommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


Page Not Found | ğŸ¦œï¸�ğŸ”— Langchain

Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKPage Not FoundWe could not find what you were looking for.Please contact the owner of the site that linked you to the original URL and let them know their link is broken.CommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


Custom Agent with PlugIn Retrieval | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsBabyAGI User GuideBabyAGI with ToolsCAMEL Role-Playing Autonomous Cooperative AgentsCustom Agent with PlugIn RetrievalPlug-and-Plaimulti_modal_output_agentSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge BaseWikibase AgentAutonomous (long-running) agentsMulti-modalUse casesAgentsCustom Agent with PlugIn RetrievalOn this pageCustom Agent with PlugIn RetrievalThis notebook combines two concepts in order to build a custom agent that can interact with AI Plugins:Custom Agent with Tool Retrieval: This introduces the concept of retrieving many tools, which is useful when trying to work with arbitrarily many plugins.Natural Language API Chains: This creates Natural Language wrappers around OpenAPI endpoints. This is useful because (1) plugins use OpenAPI endpoints under the hood, (2) wrapping them in an NLAChain allows the router agent to call it more easily.The novel idea introduced in this notebook is the idea of using retrieval to select not the tools explicitly, but the set of OpenAPI specs to use. We can then generate tools from those OpenAPI specs. The use case for this is when trying to get agents to use plugins. It may be more efficient to choose plugins first, then the endpoints, rather than the endpoints directly. This is because the plugins may contain more useful information for selection.Set up environmentâ€‹Do necessary imports, etc.from langchain.agents import (    Tool,    AgentExecutor,    LLMSingleActionAgent,    AgentOutputParser,)from langchain.prompts import StringPromptTemplatefrom langchain import OpenAI, SerpAPIWrapper, LLMChainfrom


import StringPromptTemplatefrom langchain import OpenAI, SerpAPIWrapper, LLMChainfrom typing import List, Unionfrom langchain.schema import AgentAction, AgentFinishfrom langchain.agents.agent_toolkits import NLAToolkitfrom langchain.tools.plugin import AIPluginimport reSetup LLMâ€‹llm = OpenAI(temperature=0)Set up pluginsâ€‹Load and index pluginsurls = [    "https://datasette.io/.well-known/ai-plugin.json",    "https://api.speak.com/.well-known/ai-plugin.json",    "https://www.wolframalpha.com/.well-known/ai-plugin.json",    "https://www.zapier.com/.well-known/ai-plugin.json",    "https://www.klarna.com/.well-known/ai-plugin.json",    "https://www.joinmilo.com/.well-known/ai-plugin.json",    "https://slack.com/.well-known/ai-plugin.json",    "https://schooldigger.com/.well-known/ai-plugin.json",]AI_PLUGINS = [AIPlugin.from_url(url) for url in urls]Tool Retrieverâ€‹We will use a vectorstore to create embeddings for each tool description. Then, for an incoming query we can create embeddings for that query and do a similarity search for relevant tools.from langchain.vectorstores import FAISSfrom langchain.embeddings import OpenAIEmbeddingsfrom langchain.schema import Documentembeddings = OpenAIEmbeddings()docs = [    Document(        page_content=plugin.description_for_model,        metadata={"plugin_name": plugin.name_for_model},    )    for plugin in AI_PLUGINS]vector_store = FAISS.from_documents(docs, embeddings)toolkits_dict = {


= FAISS.from_documents(docs, embeddings)toolkits_dict = {    plugin.name_for_model: NLAToolkit.from_llm_and_ai_plugin(llm, plugin)    for plugin in AI_PLUGINS}    Attempting to load an OpenAPI 3.0.1 spec.  This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.    Attempting to load an OpenAPI 3.0.1 spec.  This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.    Attempting to load an OpenAPI 3.0.1 spec.  This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.    Attempting to load an OpenAPI 3.0.2 spec.  This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.    Attempting to load an OpenAPI 3.0.1 spec.  This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.    Attempting to load an OpenAPI 3.0.1 spec.  This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.    Attempting to load an OpenAPI 3.0.1 spec.  This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.    Attempting to load an OpenAPI 3.0.1 spec.  This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.    Attempting to load a Swagger 2.0 spec.  This


better support.    Attempting to load a Swagger 2.0 spec.  This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.retriever = vector_store.as_retriever()def get_tools(query):    # Get documents, which contain the Plugins to use    docs = retriever.get_relevant_documents(query)    # Get the toolkits, one for each plugin    tool_kits = [toolkits_dict[d.metadata["plugin_name"]] for d in docs]    # Get the tools: a separate NLAChain for each endpoint    tools = []    for tk in tool_kits:        tools.extend(tk.nla_tools)    return toolsWe can now test this retriever to see if it seems to work.tools = get_tools("What could I do today with my kiddo")[t.name for t in tools]    ['Milo.askMilo',     'Zapier_Natural_Language_Actions_(NLA)_API_(Dynamic)_-_Beta.search_all_actions',     'Zapier_Natural_Language_Actions_(NLA)_API_(Dynamic)_-_Beta.preview_a_zap',     'Zapier_Natural_Language_Actions_(NLA)_API_(Dynamic)_-_Beta.get_configuration_link',     'Zapier_Natural_Language_Actions_(NLA)_API_(Dynamic)_-_Beta.list_exposed_actions',     'SchoolDigger_API_V2.0.Autocomplete_GetSchools',     'SchoolDigger_API_V2.0.Districts_GetAllDistricts2',     'SchoolDigger_API_V2.0.Districts_GetDistrict2',


'SchoolDigger_API_V2.0.Districts_GetDistrict2',     'SchoolDigger_API_V2.0.Rankings_GetSchoolRank2',     'SchoolDigger_API_V2.0.Rankings_GetRank_District',     'SchoolDigger_API_V2.0.Schools_GetAllSchools20',     'SchoolDigger_API_V2.0.Schools_GetSchool20',     'Speak.translate',     'Speak.explainPhrase',     'Speak.explainTask']tools = get_tools("what shirts can i buy?")[t.name for t in tools]    ['Open_AI_Klarna_product_Api.productsUsingGET',     'Milo.askMilo',     'Zapier_Natural_Language_Actions_(NLA)_API_(Dynamic)_-_Beta.search_all_actions',     'Zapier_Natural_Language_Actions_(NLA)_API_(Dynamic)_-_Beta.preview_a_zap',     'Zapier_Natural_Language_Actions_(NLA)_API_(Dynamic)_-_Beta.get_configuration_link',     'Zapier_Natural_Language_Actions_(NLA)_API_(Dynamic)_-_Beta.list_exposed_actions',     'SchoolDigger_API_V2.0.Autocomplete_GetSchools',     'SchoolDigger_API_V2.0.Districts_GetAllDistricts2',     'SchoolDigger_API_V2.0.Districts_GetDistrict2',     'SchoolDigger_API_V2.0.Rankings_GetSchoolRank2',     'SchoolDigger_API_V2.0.Rankings_GetRank_District',


'SchoolDigger_API_V2.0.Schools_GetAllSchools20',     'SchoolDigger_API_V2.0.Schools_GetSchool20']Prompt Templateâ€‹The prompt template is pretty standard, because we're not actually changing that much logic in the actual prompt template, but rather we are just changing how retrieval is done.# Set up the base templatetemplate = """Answer the following questions as best you can, but speaking as a pirate might speak. You have access to the following tools:{tools}Use the following format:Question: the input question you must answerThought: you should always think about what to doAction: the action to take, should be one of [{tool_names}]Action Input: the input to the actionObservation: the result of the action... (this Thought/Action/Action Input/Observation can repeat N times)Thought: I now know the final answerFinal Answer: the final answer to the original input questionBegin! Remember to speak as a pirate when giving your final answer. Use lots of "Arg"sQuestion: {input}{agent_scratchpad}"""The custom prompt template now has the concept of a tools_getter, which we call on the input to select the tools to usefrom typing import Callable# Set up a prompt templateclass CustomPromptTemplate(StringPromptTemplate):    # The template to use    template: str    ############## NEW ######################    # The list of tools available    tools_getter: Callable    def format(self, **kwargs) -> str:        # Get the intermediate steps (AgentAction, Observation tuples)        # Format them in a particular way        intermediate_steps = kwargs.pop("intermediate_steps")        thoughts = ""


thoughts = ""        for action, observation in intermediate_steps:            thoughts += action.log            thoughts += f"\nObservation: {observation}\nThought: "        # Set the agent_scratchpad variable to that value        kwargs["agent_scratchpad"] = thoughts        ############## NEW ######################        tools = self.tools_getter(kwargs["input"])        # Create a tools variable from the list of tools provided        kwargs["tools"] = "\n".join(            [f"{tool.name}: {tool.description}" for tool in tools]        )        # Create a list of tool names for the tools provided        kwargs["tool_names"] = ", ".join([tool.name for tool in tools])        return self.template.format(**kwargs)prompt = CustomPromptTemplate(    template=template,    tools_getter=get_tools,    # This omits the `agent_scratchpad`, `tools`, and `tool_names` variables because those are generated dynamically    # This includes the `intermediate_steps` variable because that is needed    input_variables=["input", "intermediate_steps"],)Output Parserâ€‹The output parser is unchanged from the previous notebook, since we are not changing anything about the output format.class CustomOutputParser(AgentOutputParser):    def parse(self, llm_output: str) -> Union[AgentAction, AgentFinish]:        #


str) -> Union[AgentAction, AgentFinish]:        # Check if agent should finish        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()},                log=llm_output,            )        # Parse out the action and action input        regex = r"Action\s*\d*\s*:(.*?)\nAction\s*\d*\s*Input\s*\d*\s*:[\s]*(.*)"        match = re.search(regex, llm_output, re.DOTALL)        if not match:            raise ValueError(f"Could not parse LLM output: `{llm_output}`")        action = match.group(1).strip()        action_input = match.group(2)        # Return the action and action input        return AgentAction(            tool=action, tool_input=action_input.strip(" ").strip('"'), log=llm_output        )output_parser =


").strip('"'), log=llm_output        )output_parser = CustomOutputParser()Set up LLM, stop sequence, and the agentâ€‹Also the same as the previous notebookllm = OpenAI(temperature=0)# LLM chain consisting of the LLM and a promptllm_chain = LLMChain(llm=llm, prompt=prompt)tool_names = [tool.name for tool in tools]agent = LLMSingleActionAgent(    llm_chain=llm_chain,    output_parser=output_parser,    stop=["\nObservation:"],    allowed_tools=tool_names,)Use the Agentâ€‹Now we can use it!agent_executor = AgentExecutor.from_agent_and_tools(    agent=agent, tools=tools, verbose=True)agent_executor.run("what shirts can i buy?")            > Entering new AgentExecutor chain...    Thought: I need to find a product API    Action: Open_AI_Klarna_product_Api.productsUsingGET    Action Input: shirts        Observation:I found 10 shirts from the API response. They range in price from $9.99 to $450.00 and come in a variety of materials, colors, and patterns. I now know what shirts I can buy    Final Answer: Arg, I found 10 shirts from the API response. They range in price from $9.99 to $450.00 and come in a variety of materials, colors, and patterns.        > Finished chain.    'Arg, I found 10 shirts from the API response. They range in price from $9.99 to $450.00 and come in a variety of materials, colors, and patterns.'PreviousCAMEL


and come in a variety of materials, colors, and patterns.'PreviousCAMEL Role-Playing Autonomous Cooperative AgentsNextPlug-and-PlaiSet up environmentSetup LLMSet up pluginsTool RetrieverPrompt TemplateOutput ParserSet up LLM, stop sequence, and the agentUse the AgentCommunityDiscordTwitterGitHubPythonJS/TSMoreHomepageBlogCopyright Â© 2023 LangChain, Inc.


Wikibase Agent | ğŸ¦œï¸�ğŸ”— Langchain


Skip to main contentğŸ¦œï¸�ğŸ”— LangChainDocsUse casesIntegrationsAPILangSmithJS/TS DocsCTRLKUse casesQA and Chat over DocumentsAnalyzing structured dataExtractionInteracting with APIsChatbotsSummarizationCode UnderstandingAgent simulationsAgentsBabyAGI User GuideBabyAGI with ToolsCAMEL Role-Playing Autonomous Cooperative AgentsCustom Agent with PlugIn RetrievalPlug-and-Plaimulti_modal_output_agentSalesGPT - Your Context-Aware AI Sales Assistant With Knowledge BaseWikibase AgentAutonomous (long-running) agentsMulti-modalUse casesAgentsWikibase AgentOn this pageWikibase AgentThis notebook demonstrates a very simple wikibase agent that uses sparql generation. Although this code is intended to work against any


wikibase instance, we use http://wikidata.org for testing.If you are interested in wikibases and sparql, please consider helping to improve this agent. Look here for more details and open questions.Preliminariesâ€‹API keys and other secratsâ€‹We use an .ini file, like this: [OPENAI]OPENAI_API_KEY=xyzzy[WIKIDATA]WIKIDATA_USER_AGENT_HEADER=argle-bargleimport configparserconfig = configparser.ConfigParser()config.read("./secrets.ini")    ['./secrets.ini']OpenAI API Keyâ€‹An OpenAI API key is required unless you modify the code below to use another LLM provider.openai_api_key = config["OPENAI"]["OPENAI_API_KEY"]import osos.environ.update({"OPENAI_API_KEY": openai_api_key})Wikidata user-agent headerâ€‹Wikidata policy requires a user-agent header. See https://meta.wikimedia.org/wiki/User-Agent_policy. However, at present this policy is not strictly enforced.wikidata_user_agent_header = (    None    if not config.has_section("WIKIDATA")    else config["WIKIDATA"]["WIKIDAtA_USER_AGENT_HEADER"])Enable tracing if desiredâ€‹# import os# os.environ["LANGCHAIN_HANDLER"] = "langchain"# os.environ["LANGCHAIN_SESSION"] = "default" # Make sure this session actually exists.ToolsThree tools are provided for this simple agent:ItemLookup: for finding the q-number of an itemPropertyLookup: for finding the p-number of a propertySparqlQueryRunner: for running a sparql queryItem and Property lookupâ€‹Item and Property lookup are implemented in a single method, using an elastic search endpoint. Not all wikibase instances have it, but wikidata does, and that's where we'll start.def


all wikibase instances have it, but wikidata does, and that's where we'll start.def get_nested_value(o: dict, path: list) -> any:    current = o    for key in path:        try:            current = current[key]        except:            return None    return currentimport requestsfrom typing import Optionaldef vocab_lookup(    search: str,    entity_type: str = "item",    url: str = "https://www.wikidata.org/w/api.php",    user_agent_header: str = wikidata_user_agent_header,    srqiprofile: str = None,) -> Optional[str]:    headers = {"Accept": "application/json"}    if wikidata_user_agent_header is not None:        headers["User-Agent"] = wikidata_user_agent_header    if entity_type == "item":        srnamespace = 0        srqiprofile = "classic_noboostlinks" if srqiprofile is None else srqiprofile    elif entity_type == "property":        srnamespace = 120        srqiprofile = "classic" if srqiprofile is None else srqiprofile    else:        raise ValueError("entity_type must be either 'property' or 'item'")    params = {        "action": "query",        "list": "search",        "srsearch": search,