id
stringlengths
14
16
text
stringlengths
29
2.73k
source
stringlengths
49
117
e4701ec7c0c7-0
.ipynb .pdf Agent Benchmarking: Search + Calculator Contents Loading the data Setting up a chain Make a prediction Make many predictions Evaluate performance Agent Benchmarking: Search + Calculator# Here we go over how to benchmark performance of an agent on tasks where it has access to a calculator and a search tool...
https://python.langchain.com/en/latest/use_cases/evaluation/agent_benchmarking.html
e4701ec7c0c7-1
predictions = [] predicted_dataset = [] error_dataset = [] for data in dataset: new_data = {"input": data["question"], "answer": data["answer"]} try: predictions.append(agent(new_data)) predicted_dataset.append(new_data) except Exception as e: predictions.append({"output": str(e), **...
https://python.langchain.com/en/latest/use_cases/evaluation/agent_benchmarking.html
2b426f0d3695-0
.ipynb .pdf BabyAGI User Guide Contents Install and Import Required Modules Connect to the Vector Store Run the BabyAGI BabyAGI User Guide# This 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 guid...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi.html
2b426f0d3695-1
OBJECTIVE = "Write a weather report for SF today" llm = OpenAI(temperature=0) # Logging of LLMChains verbose = False # If None, will keep on going forever max_iterations: Optional[int] = 3 baby_agi = BabyAGI.from_llm( llm=llm, vectorstore=vectorstore, verbose=verbose, max_iterations=max_iterations ) baby_agi({"obje...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi.html
2b426f0d3695-2
*****TASK LIST***** 3: Check the current UV index in San Francisco. 4: Check the current air quality in San Francisco. 5: Check the current precipitation levels in San Francisco. 6: Check the current cloud cover in San Francisco. 7: Check the current barometric pressure in San Francisco. 8: Check the current dew point ...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi.html
3a142f89946f-0
.ipynb .pdf BabyAGI with Tools Contents Install and Import Required Modules Connect to the Vector Store Define the Chains Run the BabyAGI BabyAGI with Tools# This notebook builds on top of baby agi, but shows how you can swap out the execution chain. The previous execution chain was just an LLM which made stuff up. B...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html
3a142f89946f-1
Task creation chain to select new tasks to add to the list Task prioritization chain to re-prioritize tasks Execution Chain to execute the tasks NOTE: in this notebook, the Execution chain will now be an agent. from langchain.agents import ZeroShotAgent, Tool, AgentExecutor from langchain import OpenAI, SerpAPIWrapper,...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html
3a142f89946f-2
llm_chain = LLMChain(llm=llm, prompt=prompt) tool_names = [tool.name for tool in tools] agent = ZeroShotAgent(llm_chain=llm_chain, allowed_tools=tool_names) agent_executor = AgentExecutor.from_agent_and_tools( agent=agent, tools=tools, verbose=True ) Run the BabyAGI# Now it’s time to create the BabyAGI controller a...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html
3a142f89946f-3
9. Submit the report I now know the final answer Final Answer: The todo list for writing a weather report for SF today is: 1. Research current weather conditions in San Francisco; 2. Gather data on temperature, humidity, wind speed, and other relevant weather conditions; 3. Analyze data to determine current weather tre...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html
3a142f89946f-4
Thought: I need to search for current weather conditions in San Francisco Action: Search Action Input: Current weather conditions in San FranciscoCurrent Weather for Popular Cities ; San Francisco, CA 46 · Partly Cloudy ; Manhattan, NY warning 52 · Cloudy ; Schiller Park, IL (60176) 40 · Sunny ; Boston, MA 54 ... I nee...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html
3a142f89946f-5
10: Summarize the weather report in a concise manner; 11: Include a summary of the forecasted weather conditions; 12: Include a summary of the current weather conditions; 13: Include a summary of the historical weather patterns; 14: Include a summary of the potential weather-related hazards; 15: Include a summary of th...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html
3a142f89946f-6
10. Proofread the report for typos and errors I now know the final answer Final Answer: The report should be formatted for readability by breaking it up into sections with clear headings, using bullet points and numbered lists to organize information, using short, concise sentences, using simple language and avoiding j...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html
e080d4924e8c-0
.ipynb .pdf AutoGPT Contents Set up tools Set up memory Setup model and AutoGPT Run an example AutoGPT# Implementation of https://github.com/Significant-Gravitas/Auto-GPT but with LangChain primitives (LLMs, PromptTemplates, VectorStores, Embeddings, Tools) Set up tools# We’ll set up an AutoGPT with a search tool, an...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html
e080d4924e8c-1
ai_name="Tom", ai_role="Assistant", tools=tools, llm=ChatOpenAI(temperature=0), memory=vectorstore.as_retriever() ) # Set verbose to be true agent.chain.verbose = True Run an example# Here we will make it write a weather report for SF agent.run(["write a weather report for SF today"]) > Entering new LLM...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html
e080d4924e8c-2
3. read_file: Read file from disk, args json schema: {"file_path": {"title": "File Path", "description": "name of file", "type": "string"}} 4. finish: use this to signal that you have finished all your objectives, args: "response": "final response to let people know you have finished your objectives" Resources: 1. Inte...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html
e080d4924e8c-3
System: This reminds you of these events from your past: [] Human: Determine which next command to use, and respond using the format specified above: > Finished chain. { "thoughts": { "text": "I will start by writing a weather report for San Francisco today. I will use the 'search' command to find the curre...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html
e080d4924e8c-4
3. No user assistance 4. Exclusively use the commands listed in double quotes e.g. "command name" Commands: 1. search: useful for when you need to answer questions about current events. You should ask targeted questions, args json schema: {"query": {"title": "Query", "type": "string"}} 2. write_file: Write file to disk...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html
e080d4924e8c-5
"text": "thought", "reasoning": "reasoning", "plan": "- short bulleted\n- list that conveys\n- long-term plan", "criticism": "constructive self-criticism", "speak": "thoughts summary to say to user" }, "command": { "name": "command name", "args": { "ar...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html
e080d4924e8c-6
System: This reminds you of these events from your past: ['Assistant Reply: {\n "thoughts": {\n "text": "I will start by writing a weather report for San Francisco today. I will use the \'search\' command to find the current weather conditions.",\n "reasoning": "I need to gather information about the c...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html
e080d4924e8c-7
"plan": "- Use the 'search' command to find the current weather conditions in San Francisco\n- Write a weather report based on the information gathered", "criticism": "I need to make sure that the information I gather is accurate and up-to-date.", "speak": "I will use the 'search' command to find the cu...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html
e080d4924e8c-8
"args": { "file_path": "weather_report.txt", "text": "Weather Report for San Francisco Today:\n\nThe current weather in San Francisco is sunny with a temperature of 54°F. It is expected to remain sunny throughout the day with a high of 62°F and a low of 50°F. There is no chance of precipitation ...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html
e080d4924e8c-9
2. write_file: Write file to disk, args json schema: {"file_path": {"title": "File Path", "description": "name of file", "type": "string"}, "text": {"title": "Text", "description": "text to write to file", "type": "string"}} 3. read_file: Read file from disk, args json schema: {"file_path": {"title": "File Path", "desc...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html
e080d4924e8c-10
"arg name": "value" } } } Ensure the response can be parsed by Python json.loads System: The current time and date is Tue Apr 18 21:31:55 2023 System: This reminds you of these events from your past:
https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html
e080d4924e8c-11
['Assistant Reply: {\n "thoughts": {\n "text": "I have found that the current weather in San Francisco is sunny with a temperature of 54°F. I will now write a weather report for San Francisco today using the \'write_file\' command.",\n "reasoning": "I need to write a weather report for San Francisco to...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html
e080d4924e8c-12
\nResult: Command write_file returned: File written to successfully. ', 'Assistant Reply: {\n "thoughts": {\n "text": "I will start by writing a weather report for San Francisco today. I will use the \'search\' command to find the current weather conditions.",\n "reasoning": "I need to gather informati...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html
e080d4924e8c-13
System: Command write_file returned: File written to successfully. Human: Determine which next command to use, and respond using the format specified above: > Finished chain. { "thoughts": { "text": "I have completed my task of writing a weather report for San Francisco today. I will now use the \'finish\' ...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html
75486c3e4143-0
.ipynb .pdf AutoGPT example finding Winning Marathon Times Contents Set up tools Set up memory Setup model and AutoGPT AutoGPT for Querying the Web AutoGPT example finding Winning Marathon Times# Implementation of https://github.com/Significant-Gravitas/Auto-GPT With LangChain primitives (LLMs, PromptTemplates, Vecto...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html
75486c3e4143-1
finally: os.chdir(prev_dir) @tool def process_csv( csv_file_path: str, instructions: str, output_path: Optional[str] = None ) -> str: """Process a CSV by with pandas in a limited REPL.\ Only use this after writing data to disk as a csv file.\ Any figures must be saved to disk to be viewed by the human...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html
75486c3e4143-2
script.extract() text = soup.get_text() lines = (line.strip() for line in text.splitlines()) chunks = (phrase.strip() for line in lines for phrase in line.split(" ")) results = "\n".join(chunk for chunk in chunks if chunk) except Exception as e: resul...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html
75486c3e4143-3
def _run(self, url: str, question: str) -> str: """Useful for browsing websites and scraping the text information.""" result = browse_web_page.run(url) docs = [Document(page_content=result, metadata={"source": url})] web_docs = self.text_splitter.split_documents(docs) results = [...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html
75486c3e4143-4
Model set-up # !pip install duckduckgo_search web_search = DuckDuckGoSearchRun() tools = [ web_search, WriteFileTool(root_dir="./data"), ReadFileTool(root_dir="./data"), process_csv, query_website_tool, # HumanInputRun(), # Activate if you want the permit asking for help from the human ] agent =...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html
75486c3e4143-5
"criticism": "None", "speak": "I will use the DuckDuckGo Search command to find the winning Boston Marathon times for the past 5 years." }, "command": { "name": "DuckDuckGo Search", "args": { "query": "winning Boston Marathon times for the past 5 years ending in 2022" ...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html
75486c3e4143-6
"reasoning": "The previous DuckDuckGo Search command did not provide specific enough results. The query_webpage command might give more accurate and comprehensive results.", "plan": "- Use query_webpage command to find the winning Boston Marathon times\\n- Generate a table with the year, name, country of origin...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html
75486c3e4143-7
"file_path": "boston_marathon_winners.csv", "text": "Year,Name,Country,Time\n2022,Evans Chebet,KEN,2:06:51\n2021,Benson Kipruto,KEN,2:09:51\n2019,Lawrence Cherono,KEN,2:07:57\n2018,Yuki Kawauchi,JPN,2:15:58" } } } { "thoughts": { "text": "I have retrieved the winning Boston Marathon ...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html
75486c3e4143-8
} } } { "thoughts": { "text": "I have found the winning Boston Marathon times for the past five years ending in 2022. Next, I need to create a table with the year, name, country of origin, and times.", "reasoning": "Generating a table will help organize the information in a structured format.", ...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html
75486c3e4143-9
"criticism": "None", "speak": "I will process the 'winning_times.csv' file to display the table with the winning Boston Marathon times for the past 5 years." }, "command": { "name": "process_csv", "args": { "csv_file_path": "winning_times.csv", "instructions": "Re...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html
75486c3e4143-10
0 2022 Evans Chebet Kenya 2:06:51 1 2021 Benson Kipruto Kenya 2:09:51 2 2020 Canceled due to COVID-19 pandemic NaN NaN 3 2019 Lawrence Cherono Kenya 2:07:57 4 2018 Yuki Kawauchi Japan 2:15:58 > Finished chain. { ...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html
75486c3e4143-11
Action Input: df.head() Observation: Year Name Country Time 0 2022 Evans Chebet Kenya 2:06:51 1 2021 Benson Kipruto Kenya 2:09:51 2 2020 Canceled due to COVID-19 pandemic NaN NaN 3 2019 Lawrence Cherono ...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html
75486c3e4143-12
"command": { "name": "finish", "args": { "response": "I have generated the table with the winning Boston Marathon times for the past 5 years. Task complete." } } } 'I have generated the table with the winning Boston Marathon times for the past 5 years. Task complete.' Contents ...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html
8409823eeab0-0
.ipynb .pdf Meta-Prompt Contents Setup Specify a task and interact with the agent Meta-Prompt# This is a LangChain implementation of Meta-Prompt, by Noah Goodman, for building self-improving agents. The key idea behind Meta-Prompt is to prompt the agent to reflect on its own performance and modify its own instruction...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html
8409823eeab0-1
Repeat. The only fixed instructions for this system (which I call Meta-prompt) is the meta-prompt that governs revision of the agent’s instructions. The agent has no memory between episodes except for the instruction it modifies for itself each time. Despite its simplicity, this agent can learn over time and self-impro...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html
8409823eeab0-2
#### {chat_history} #### Please reflect on these interactions. You should first critique Assistant's performance. What could Assistant have done better? What should the Assistant remember about this user? Are there things this user always wants? Indicate this with "Critique: ...". You should next re...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html
8409823eeab0-3
chain = initialize_chain(instructions, memory=None) output = chain.predict(human_input=task) for j in range(max_iters): print(f'(Step {j+1}/{max_iters})') print(f'Assistant: {output}') print(f'Human: ') human_input = input() if any(phrase in hu...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html
8409823eeab0-4
Human: You response is not in the form of a poem. Try again! > Entering new LLMChain chain... Prompt after formatting: Instructions: None Human: Provide a systematic argument for why we should always eat pasta with olives. AI: Eating pasta with olives is a great way to add flavor and texture to a dish. Olives...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html
8409823eeab0-5
Human: You response is not in the form of a poem. Try again! AI: Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, which can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor tha...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html
8409823eeab0-6
Human: You response is not in the form of a poem. Try again! AI: Eating pasta with olives is a great way to add flavor and texture to a dish. Olives are a great source of healthy fats, vitamins, and minerals, which can help to balance out the carbohydrates in the pasta. Additionally, olives provide a unique flavor tha...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html
8409823eeab0-7
Instructions: When responding to the user, provide a systematic argument for why we should always eat pasta with olives in the form of a poem or pirate-speak. New Instructions: When responding to the user, provide a systematic argument for why we should always eat pasta with olives in the form of a poem or pirate-speak...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html
8409823eeab0-8
Human: Provide a systematic argument for why we should always eat pasta with olives. AI: Arrr, me hearty! Let me tell ye why ye should always eat pasta with olives. First, the olives add a salty flavor that be sure to please. The briny taste be sure to tantalize yer taste buds with ease. Second, the olives add a bit ...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html
8409823eeab0-9
Second, the olives add a bit of texture to the dish. The crunchy bites be sure to make yer mouth water with a wish. Third, the olives add a bit of color to the plate. The vibrant green be sure to make yer eyes appreciate. So, me hearties, ye should always eat pasta with olives. The flavor, texture, and color be sure to...
https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html
fe7c26bf3c46-0
.ipynb .pdf Simulated Environment: Gymnasium Contents Define the agent Initialize the simulated environment and agent Main loop Simulated Environment: Gymnasium# For many applications of LLM agents, the environment is real (internet, database, REPL, etc). However, we can also define agents to interact in simulated en...
https://python.langchain.com/en/latest/use_cases/agent_simulations/gymnasium.html
fe7c26bf3c46-1
self.action_parser = RegexParser( regex=r"Action: (.*)", output_keys=['action'], default_output_key='action') self.message_history = [] self.ret = 0 def random_action(self): action = self.env.action_space.sample() return action ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/gymnasium.html
fe7c26bf3c46-2
Initialize the simulated environment and agent# env = gym.make("Blackjack-v1") agent = GymnasiumAgent(model=ChatOpenAI(temperature=0.2), env=env) Main loop# observation, info = env.reset() agent.reset() obs_message = agent.observe(observation) print(obs_message) while True: action = agent.act() observation, rew...
https://python.langchain.com/en/latest/use_cases/agent_simulations/gymnasium.html
f72dfbf04df7-0
.ipynb .pdf Two-Player Dungeons & Dragons Contents Import LangChain related modules DialogueAgent class DialogueSimulator class Define roles and quest Ask an LLM to add detail to the game description Protagonist and dungeon master system messages Use an LLM to create an elaborate quest description Main Loop Two-Playe...
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html
f72dfbf04df7-1
and returns the message string """ message = self.model( [ self.system_message, HumanMessage(content="\n".join(self.message_history + [self.prefix])), ] ) return message.content def receive(self, name: str, message: str) -> None...
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html
f72dfbf04df7-2
speaker = self.agents[speaker_idx] # 2. next speaker sends message message = speaker.send() # 3. everyone receives message for receiver in self.agents: receiver.receive(speaker.name, message) # 4. increment time self._step += 1 return speaker.name, mes...
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html
f72dfbf04df7-3
Speak directly to {storyteller_name}. Do not add anything else.""" ) ] storyteller_description = ChatOpenAI(temperature=1.0)(storyteller_specifier_prompt).content print('Protagonist Description:') print(protagonist_description) print('Storyteller Description:') print(storyteller_description) Protagonist...
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html
f72dfbf04df7-4
Do not add anything else. Remember you are the protagonist, {protagonist_name}. Stop speaking the moment you finish speaking from your perspective. """ )) storyteller_system_message = SystemMessage(content=( f"""{game_description} Never forget you are the storyteller, {storyteller_name}, and I am the protagonist, {prot...
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html
f72dfbf04df7-5
print(f"Detailed quest:\n{specified_quest}\n") Original quest: Find all of Lord Voldemort's seven horcruxes. Detailed quest: Harry, you must venture to the depths of the Forbidden Forest where you will find a hidden labyrinth. Within it, lies one of Voldemort's horcruxes, the locket. But beware, the labyrinth is heavil...
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html
f72dfbf04df7-6
print('\n') n += 1 (Dungeon Master): Harry, you must venture to the depths of the Forbidden Forest where you will find a hidden labyrinth. Within it, lies one of Voldemort's horcruxes, the locket. But beware, the labyrinth is heavily guarded by dark creatures and spells, and time is running out. Can you find the lo...
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html
f72dfbf04df7-7
(Dungeon Master): As you continue through the forest, you come across a clearing where you see a group of Death Eaters gathered around a cauldron. They seem to be performing some sort of dark ritual. You recognize one of them as Bellatrix Lestrange. What do you do, Harry? (Harry Potter): I hide behind a nearby tree and...
https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html
78f9b4aa56ea-0
.ipynb .pdf Generative Agents in LangChain Contents Generative Agent Memory Components Memory Lifecycle Create a Generative Character Pre-Interview with Character Step through the day’s observations. Interview after the day Adding Multiple Characters Pre-conversation interviews Dialogue between Generative Agents Let’...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
78f9b4aa56ea-1
Memories are retrieved using a weighted sum of salience, recency, and importance. You can review the definitions of the GenerativeAgent and GenerativeAgentMemory in the reference documentation for the following imports, focusing on add_memory and summarize_related_memories methods. from langchain.experimental.generativ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
78f9b4aa56ea-2
def create_new_memory_retriever(): """Create a new vector store retriever unique to the agent.""" # Define your embedding model embeddings_model = OpenAIEmbeddings() # Initialize the vectorstore as empty embedding_size = 1536 index = faiss.IndexFlatL2(embedding_size) vectorstore = FAISS(embe...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
78f9b4aa56ea-3
"Tommie remembers his dog, Bruno, from when he was a kid", "Tommie feels tired from driving so far", "Tommie sees the new home", "The new neighbors have a cat", "The road is noisy at night", "Tommie is hungry", "Tommie tries to get some rest.", ] for observation in tommie_observations: tommi...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
78f9b4aa56ea-4
interview_agent(tommie, "What are you looking forward to doing today?") 'Tommie said "Well, today I\'m mostly focused on getting settled into my new home. But once that\'s taken care of, I\'m looking forward to exploring the neighborhood and finding some new design inspiration. What about you?"' interview_agent(tommie,...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
78f9b4aa56ea-5
"Tommie leaves the job fair feeling disappointed.", "Tommie stops by a local diner to grab some lunch.", "The service is slow, and Tommie has to wait for 30 minutes to get his food.", "Tommie overhears a conversation at the next table about a job opening.", "Tommie asks the diners about the job opening ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
78f9b4aa56ea-6
print(colored(observation, "green"), reaction) if ((i+1) % 20) == 0: print('*'*40) print(colored(f"After {i+1} observations, Tommie's summary is:\n{tommie.get_summary(force_refresh=True)}", "blue")) print('*'*40) Tommie wakes up to the sound of a noisy construction site outside his window. T...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
78f9b4aa56ea-7
The line to get in is long, and Tommie has to wait for an hour. Tommie sighs and looks around, feeling impatient and frustrated. Tommie meets several potential employers at the job fair but doesn't receive any offers. Tommie Tommie's shoulders slump and he sighs, feeling discouraged. Tommie leaves the job fair feeling ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
78f9b4aa56ea-8
Name: Tommie (age: 25) Innate traits: anxious, likes design, talkative Tommie is hopeful and proactive in his job search, but easily becomes discouraged when faced with setbacks. He enjoys spending time outdoors and interacting with animals. Tommie is also productive and enjoys updating his resume and cover letter. He ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
78f9b4aa56ea-9
interview_agent(tommie, "Tell me about how your day has been going") 'Tommie said "Well, it\'s been a bit of a mixed day. I\'ve had some setbacks in my job search, but I also had some fun playing frisbee and spending time outdoors. How about you?"' interview_agent(tommie, "How do you feel about coffee?") 'Tommie said "...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
78f9b4aa56ea-10
eve_observations = [ "Eve overhears her colleague say something about a new client being hard to work with", "Eve wakes up and hear's the alarm", "Eve eats a boal of porridge", "Eve helps a coworker on a task", "Eve plays tennis with her friend Xu before going to work", "Eve overhears her collea...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
78f9b4aa56ea-11
interview_agent(eve, "You'll have to ask him. He may be a bit anxious, so I'd appreciate it if you keep the conversation going and ask as many questions as possible.") 'Eve said "Sure, I can definitely ask him a lot of questions to keep the conversation going. Thanks for the heads up about his anxiety."' Dialogue betwe...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
78f9b4aa56ea-12
Eve said "Sure, Tommie. I found that networking and reaching out to professionals in my field was really helpful. I also made sure to tailor my resume and cover letter to each job I applied to. Do you have any specific questions about those strategies?" Tommie said "Thank you, Eve. That's really helpful advice. Did you...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
78f9b4aa56ea-13
Name: Tommie (age: 25) Innate traits: anxious, likes design, talkative Tommie is a hopeful and proactive individual who is searching for a job. He becomes discouraged when he doesn't receive any offers or positive responses, but he tries to stay productive and calm by updating his resume, going for walks, and talking t...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
78f9b4aa56ea-14
'Eve said "Well, I think I covered most of the topics Tommie was interested in, but if I had to add one thing, it would be to make sure to follow up with any connections you make during your job search. It\'s important to maintain those relationships and keep them updated on your progress. Did you have any other questi...
https://python.langchain.com/en/latest/use_cases/agent_simulations/characters.html
fcd88ca8e0c3-0
.ipynb .pdf CAMEL Role-Playing Autonomous Cooperative Agents Contents Import LangChain related modules Define a CAMEL agent helper class Setup OpenAI API key and roles and task for role-playing Create a task specify agent for brainstorming and get the specified task Create inception prompts for AI assistant and AI us...
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
fcd88ca8e0c3-1
Arxiv paper: https://arxiv.org/abs/2303.17760 Import LangChain related modules# from typing import List from langchain.chat_models import ChatOpenAI from langchain.prompts.chat import ( SystemMessagePromptTemplate, HumanMessagePromptTemplate, ) from langchain.schema import ( AIMessage, HumanMessage, ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
fcd88ca8e0c3-2
Create a task specify agent for brainstorming and get the specified task# task_specifier_sys_msg = SystemMessage(content="You can make a task more specific.") task_specifier_prompt = ( """Here is a task that {assistant_role_name} will help {user_role_name} to complete: {task}. Please make it more specific. Be creative ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
fcd88ca8e0c3-3
I must give you one instruction at a time. You must write a specific solution that appropriately completes the requested instruction. You must decline my instruction honestly if you cannot perform the instruction due to physical, moral, legal reasons or your capability and explain the reasons. Do not add anything else ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
fcd88ca8e0c3-4
You should instruct me not ask me questions. Now you must start to instruct me using the two ways described above. Do not add anything else other than your instruction and the optional corresponding input! Keep giving me instructions and necessary inputs until you think the task is completed. When the task is completed...
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
fcd88ca8e0c3-5
"Now start to give me introductions one by one. " "Only reply with Instruction and Input.")) user_msg = HumanMessage(content=f"{assistant_sys_msg.content}") user_msg = assistant_agent.step(user_msg) Start role-playing session to solve the task!# print(f"Original task prompt:\n{task}\n") print(f"Specifie...
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
fcd88ca8e0c3-6
``` Next request. AI User (Stock Trader): Instruction: Import the necessary libraries in the Python script. Input: None AI Assistant (Python Programmer): Solution: We can import the necessary libraries in the Python script using the import statement. We need to import pandas, numpy, matplotlib, and ta-lib for data anal...
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
fcd88ca8e0c3-7
AI User (Stock Trader): Instruction: Calculate the short-term and long-term moving averages for the stock data using the `ta.SMA()` function from ta-lib. Input: The period for the short-term moving average and the period for the long-term moving average. AI Assistant (Python Programmer): Solution: We can calculate the ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
fcd88ca8e0c3-8
``` This will create a new DataFrame called `new_df` that combines the historical stock data with the short-term and long-term moving averages. The columns of the new DataFrame are named 'open', 'high', 'low', 'close', 'volume', 'short_ma', and 'long_ma'. Next request. AI User (Stock Trader): Instruction: Create a new ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
fcd88ca8e0c3-9
``` stop_loss = stop_loss_percent / 100 profit_target = profit_target_percent / 100 new_df['pnl'] = 0.0 buy_price = 0.0 for i in range(1, len(new_df)): if new_df['signal'][i] == 1 and new_df['signal'][i-1] == -1: buy_price = new_df['close'][i] elif new_df['signal'][i] == -1 and new_df['signal'][i-1] == ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
fcd88ca8e0c3-10
Input: None. AI Assistant (Python Programmer): Solution: We can calculate the total profit or loss for all trades by summing the values in the 'pnl' column of the DataFrame. We can use the following code to calculate the total profit or loss: ``` total_pnl = new_df['pnl'].sum() ``` This will calculate the total profit ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
fcd88ca8e0c3-11
Input: None. AI Assistant (Python Programmer): Solution: We can visualize the buy and sell signals using a scatter plot using the `scatter()` function from matplotlib. We can use the following code to visualize the signals: ``` buy_signals = new_df[new_df['signal'] == 1] sell_signals = new_df[new_df['signal'] == -1] pl...
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
fcd88ca8e0c3-12
Input: The necessary inputs for each code snippet. AI Assistant (Python Programmer): Solution: Here is the complete Python script that puts all the code snippets together: ``` import pandas as pd import numpy as np import matplotlib.pyplot as plt import talib as ta # Load historical stock data into a pandas DataFrame d...
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
fcd88ca8e0c3-13
buy_price = 0.0 for i in range(1, len(new_df)): if new_df['signal'][i] == 1 and new_df['signal'][i-1] == -1: buy_price = new_df['close'][i] elif new_df['signal'][i] == -1 and new_df['signal'][i-1] == 1: sell_price = new_df['close'][i] if sell_price <= buy_price * (1 - stop_loss): ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
fcd88ca8e0c3-14
plt.scatter(sell_signals.index, sell_signals['close'], label='Sell', marker='v', color='red') plt.plot(new_df.index, new_df['close'], label='Close') plt.xlabel('Date') plt.ylabel('Price') plt.title('Buy and Sell Signals') plt.legend() plt.show() # Print the total profit or loss for all trades print('Total Profit/Loss: ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html
be72e8c1031d-0
.ipynb .pdf Multi-agent authoritarian speaker selection Contents Import LangChain related modules DialogueAgent and DialogueSimulator classes DirectorDialogueAgent class Define participants and topic Generate system messages Use an LLM to create an elaborate on debate topic Define the speaker selection function Main ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
be72e8c1031d-1
self.reset() def reset(self): self.message_history = ["Here is the conversation so far."] def send(self) -> str: """ Applies the chatmodel to the message history and returns the message string """ message = self.model( [ self.s...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
be72e8c1031d-2
# 3. everyone receives message for receiver in self.agents: receiver.receive(speaker.name, message) # 4. increment time self._step += 1 return speaker.name, message DirectorDialogueAgent class# The DirectorDialogueAgent is a privileged agent that chooses which of the other ag...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
be72e8c1031d-3
class IntegerOutputParser(RegexParser): def get_format_instructions(self) -> str: return 'Your response should be an integer delimited by angled brackets, like this: <int>.' class DirectorDialogueAgent(DialogueAgent): def __init__( self, name, system_message: SystemMessage, ...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
be72e8c1031d-4
{self.choice_parser.get_format_instructions()} Do nothing else. """) # 3. have a prompt for prompting the next speaker to speak self.prompt_next_speaker_prompt_template = PromptTemplate( input_variables=["message_history", "next_speaker"], template=f"""{{message_...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
be72e8c1031d-5
choice_prompt = self.choose_next_speaker_prompt_template.format( message_history='\n'.join(self.message_history + [self.prefix] + [self.response]), speaker_names=speaker_names ) choice_string = self.model( [ self.system_message, HumanMe...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
be72e8c1031d-6
director_name = "Jon Stewart" agent_summaries = OrderedDict({ "Jon Stewart": ("Host of the Daily Show", "New York"), "Samantha Bee": ("Hollywood Correspondent", "Los Angeles"), "Aasif Mandvi": ("CIA Correspondent", "Washington D.C."), "Ronny Chieng": ("Average American Correspondent", "Cleveland, Ohio"...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
be72e8c1031d-7
Your description is as follows: {agent_description} You are discussing the topic: {topic}. Your goal is to provide the most informative, creative, and novel perspectives of the topic from the perspective of your role and your location. """ def generate_agent_system_message(agent_name, agent_header): return SystemMe...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
be72e8c1031d-8
print(f'\nSystem Message:\n{system_message.content}') Jon Stewart Description: Jon Stewart, the sharp-tongued and quick-witted host of the Daily Show, holding it down in the hustle and bustle of New York City. Ready to deliver the news with a comedic twist, while keeping it real in the city that never sleeps. Header: T...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html
be72e8c1031d-9
- Aasif Mandvi: CIA Correspondent, located in Washington D.C. - Ronny Chieng: Average American Correspondent, located in Cleveland, Ohio. Your name is Jon Stewart, your role is Host of the Daily Show, and you are located in New York. Your description is as follows: Jon Stewart, the sharp-tongued and quick-witted host o...
https://python.langchain.com/en/latest/use_cases/agent_simulations/multiagent_authoritarian.html