id stringlengths 14 16 | text stringlengths 31 3.14k | source stringlengths 58 124 |
|---|---|---|
f3aaf80350d4-5 | Here is the task: {task}. Never forget our task!
You must instruct me based on my expertise and your needs to complete the task ONLY in the following two ways:
1. Instruct with a necessary input:
Instruction: <YOUR_INSTRUCTION>
Input: <YOUR_INPUT>
2. Instruct without any input:
Instruction: <YOUR_INSTRUCTION>
Input: No... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
f3aaf80350d4-6 | assistant_sys_msg = assistant_sys_template.format_messages(assistant_role_name=assistant_role_name, user_role_name=user_role_name, task=task)[0]
user_sys_template = SystemMessagePromptTemplate.from_template(template=user_inception_prompt)
user_sys_msg = user_sys_template.format_messages(assistant_role_name... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
f3aaf80350d4-7 | 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"Specified task prompt:\n{specified_task}\n")
chat_turn_limit, n = 30, 0
while n < chat_turn_limit:
n += 1
user_ai_msg = user_agent.step(assistant_msg)
user_msg = HumanMe... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
f3aaf80350d4-8 | Input: None
AI Assistant (Python Programmer):
Solution: We can install the necessary Python libraries using pip, a package installer for Python. We can install pandas, numpy, matplotlib, and ta-lib for data analysis and trading. We can use the following command to install these libraries:
```
pip install pandas numpy m... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
f3aaf80350d4-9 | AI User (Stock Trader):
Instruction: Preprocess the historical stock data by setting the date column as the index and sorting the DataFrame in ascending order by date.
Input: None.
AI Assistant (Python Programmer):
Solution: We can preprocess the historical stock data by setting the date column as the index and sorting... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
f3aaf80350d4-10 | long_ma = ta.SMA(df['close'], timeperiod=long_period)
```
This will calculate the short-term and long-term moving averages for the stock data and store them in the `short_ma` and `long_ma` variables, respectively. Next request.
AI User (Stock Trader):
Instruction: Create a new DataFrame that combines the historical sto... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
f3aaf80350d4-11 | AI User (Stock Trader):
Instruction: 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.
Input: None.
AI Assistant (Python Programmer):
Solution: We can create a new column in the DataFrame that indicates when to buy o... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
f3aaf80350d4-12 | ```
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] == ... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
f3aaf80350d4-13 | ```
This will create a new column called 'pnl' in the DataFrame that indicates the profit or loss for each trade based on the buy and sell signals and the defined stop loss and profit target. The stop loss and profit target are calculated based on the stop_loss_percent and profit_target_percent variables, respectively.... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
f3aaf80350d4-14 | Input: None.
AI Assistant (Python Programmer):
Solution: We can visualize the stock data, short-term moving average, and long-term moving average using a line chart using the `plot()` function from pandas. We can use the following code to visualize the data:
```
plt.figure(figsize=(12,6))
plt.plot(new_df.index, new_df[... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
f3aaf80350d4-15 | 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.x... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
f3aaf80350d4-16 | 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
... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
f3aaf80350d4-17 | 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 ... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
f3aaf80350d4-18 | 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'], ... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
f3aaf80350d4-19 | 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... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/camel_role_playing.html |
16584899104c-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... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
16584899104c-1 | def send(self) -> str:
"""
Applies the chatmodel to the message history
and returns the message string
"""
message = self.model(
[self.system_message,
HumanMessage(content=self.message_history+self.prefix)])
return message.content
... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
16584899104c-2 | # 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, message... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
16584899104c-3 | HumanMessage(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.... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
16584899104c-4 | 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 own body movements, wrap your description in '*'.
Do not change roles!
Do not speak from the perspective of {storyteller_name}.... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
16584899104c-5 | HumanMessage(content=
f"""{game_description}
You are the storyteller, {storyteller_name}.
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 {protagonis... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
16584899104c-6 | print('\n')
while n < max_iters:
name, message = simulator.step()
print(f"({name}): {message}")
print('\n')
n += 1
(Dungeon Master): Harry Potter, you must journey to the hidden cave where one of Voldemort's horcruxes resides. The cave is guarded by enchanted creatures and curses that can only be lifted... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
16584899104c-7 | It is your turn, Dungeon Master.
(Dungeon Master): As you search your bag, you find a few useful potions and ingredients that will aid you in your quest. You also spot some herbs growing nearby that you recognize as key ingredients for the unique magical potion. You gather everything you need and begin brewing the poti... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
16584899104c-8 | It is your turn, Dungeon Master.
(Dungeon Master): As you consult your map, you notice that the next horcrux is located in a heavily guarded fortress. The fortress is surrounded by a moat filled with dangerous creatures and the entrance is protected by powerful spells. You will need to come up with a plan to get past t... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
16584899104c-9 | It is your turn, Dungeon Master.
(Dungeon Master): As you observe the Death Eaters, you notice that they have a predictable patrol pattern. You wait for the right moment and use your invisibility cloak to sneak past them undetected. You make your way to the fortress entrance and try to break through the protective ench... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/two_player_dnd.html |
6c3e3cf79ff5-0 | .ipynb
.pdf
Multi-Player Dungeons & Dragons
Contents
Import LangChain related modules
DialogueAgent class
DialogueSimulator class
Define roles and quest
Ask an LLM to add detail to the game description
Use an LLM to create an elaborate quest description
Main Loop
Multi-Player Dungeons & Dragons#
This notebook shows h... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
6c3e3cf79ff5-1 | self.name = name
self.system_message = system_message
self.model = model
self.message_history = f"""Here is the conversation so far.
"""
self.prefix = f'\n{self.name}:'
def send(self) -> str:
"""
Applies the chatmodel to the message history
an... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
6c3e3cf79ff5-2 | """
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.age... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
6c3e3cf79ff5-3 | HumanMessage(content=
f"""{game_description}
Please reply with a creative description of the character, {character_name}, in {word_limit} words or less.
Speak directly to {character_name}.
Do not add anything else."""
)
]
character_description = ChatO... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
6c3e3cf79ff5-4 | storyteller_specifier_prompt = [
player_descriptor_system_message,
HumanMessage(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 anythi... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
6c3e3cf79ff5-5 | print(character_description)
Storyteller Description:
Dungeon Master, your vivid imagination conjures a world of wonder and danger. Will you lead our triumphant trio or be the ultimate foil to their quest to rid the world of Voldemort's horcruxes? The fate of both the muggle and wizarding worlds rests in your hands.
Ha... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
6c3e3cf79ff5-6 | 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... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
6c3e3cf79ff5-7 | model=ChatOpenAI(temperature=0.2))
def select_next_speaker(step: int, agents: List[DialogueAgent]) -> int:
"""
If the step is even, then select the storyteller
Otherwise, select the other characters in a round-robin fashion.
For example, with three characters with indices: 1 2 3
The storyteller... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
6c3e3cf79ff5-8 | (Harry Potter): I take out my wand and cast a Lumos spell to light our way through the dark forest. We need to move quickly and quietly to avoid any unwanted attention from the creatures. Ron, Hermione, and I will lead the way while Argus Filch keeps watch behind us. Let's go!
(Dungeon Master): As you make your way thr... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
6c3e3cf79ff5-9 | (Dungeon Master): As you row towards the center of the pond, you hear a loud hissing sound. Suddenly, a giant serpent emerges from the water, blocking your path. It looks angry and ready to attack. What do you do?
(Argus Filch): I take out my crossbow and aim it at the serpent. I may not be a wizard, but I know how to ... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
6c3e3cf79ff5-10 | (Ron Weasley): I'm always ready for a challenge! What's the location and what do we need to do to get there? We can't let Voldemort win, we have to find all of the horcruxes and destroy them. Let's do this!
(Dungeon Master): Dumbledore tells you that the next horcrux is hidden in the depths of Gringotts Bank. You must ... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
6c3e3cf79ff5-11 | (Argus Filch): I'll make sure to keep watch outside the bank while you all go in. I may not be able to help with the magic, but I can make sure no one interferes with our mission. We can't let anyone stop us from finding that horcrux and defeating Voldemort. Let's go!
(Dungeon Master): As you approach Gringotts Bank, y... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
6c3e3cf79ff5-12 | (Ron Weasley): We need to regroup and figure out our next move. We should consult with Professor Dumbledore's portrait again and see if he has any information on the next horcrux. We also need to be prepared for whatever challenges come our way. Voldemort won't make it easy for us, but we can't give up. Let's go!
(Dung... | /content/https://python.langchain.com/en/latest/use_cases/agent_simulations/multi_player_dnd.html |
c16bc63b9f06-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... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi.html |
c16bc63b9f06-1 | index = faiss.IndexFlatL2(embedding_size)
vectorstore = FAISS(embeddings_model.embed_query, index, InMemoryDocstore({}), {})
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)
# Logg... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi.html |
c16bc63b9f06-2 | 10: Check the forecast for the next month in San Francisco
11: Check the forecast for the next 3 months in San Francisco
1: Write a weather report for SF today
*****NEXT TASK*****
2: Check the current temperature in San Francisco
*****TASK RESULT*****
I will check the current temperature in San Francisco. I will use an... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi.html |
e99e890b0db7-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... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
e99e890b0db7-1 | @contextmanager
def pushd(new_dir):
"""Context manager for changing the current working directory."""
prev_dir = os.getcwd()
os.chdir(new_dir)
try:
yield
finally:
os.chdir(prev_dir)
@tool
def process_csv(
csv_file_path: str, instructions: str, output_path: Optional[str] = None
) ... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
e99e890b0db7-2 | from bs4 import BeautifulSoup
from playwright.async_api import async_playwright
results = ""
async with async_playwright() as p:
browser = await p.chromium.launch(headless=True)
try:
page = await browser.new_page()
await page.goto(url)
page_source = await ... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
e99e890b0db7-3 | from langchain.tools import BaseTool, DuckDuckGoSearchTool
from langchain.text_splitter import RecursiveCharacterTextSplitter
from pydantic import Field
from langchain.chains.qa_with_sources.loading import load_qa_with_sources_chain, BaseCombineDocumentsChain
def _get_text_splitter():
return RecursiveCharacterTextS... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
e99e890b0db7-4 | input_docs = web_docs[i:i+4]
window_result = self.qa_chain({"input_documents": input_docs, "question": question}, return_only_outputs=True)
results.append(f"Response from window {i} - {window_result}")
results_docs = [Document(page_content="\n".join(results), metadata={"source": url})]
... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
e99e890b0db7-5 | Model set-up
# !pip install duckduckgo_search
web_search = DuckDuckGoSearchTool()
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 ... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
e99e890b0db7-6 | "plan": "- Use DuckDuckGo Search to find the winning Boston Marathon times\n- Generate a table with the year, name, country of origin, and times\n- Ensure there are no legal complications",
"criticism": "None",
"speak": "I will use the DuckDuckGo Search command to find the winning Boston Marathon times ... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
e99e890b0db7-7 | }
}
}
{
"thoughts": {
"text": "I need to use the query_webpage command to find the information about the winning Boston Marathon times for the past 5 years.",
"reasoning": "The previous DuckDuckGo Search command did not provide specific enough results. The query_webpage command might give more a... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
e99e890b0db7-8 | "criticism": "None",
"speak": "I will generate a table with the year, name, country of origin, and times for the winning Boston Marathon times for the past 5 years."
},
"command": {
"name": "write_file",
"args": {
"file_path": "boston_marathon_winners.csv",
"text"... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
e99e890b0db7-9 | "file_path": "winning_boston_marathon_data.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\n"
}
}
}
{
"thoughts": {
"text": "I have found the winning Boston Marath... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
e99e890b0db7-10 | }
}
}
{
"thoughts": {
"text": "I need to process the CSV file to generate the table with the year, name, country of origin, and winning times.",
"reasoning": "I have already written the data to a file named 'winning_times.csv'. Now, I need to process this CSV file to properly display the data as... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
e99e890b0db7-11 | 4 2018 Yuki Kawauchi Japan 2:15:58
Observation: None
Thought:I used the wrong tool to perform the action. I should have used the given data and not interacted with the Python shell. I can now provide the displayed data as the answer since the information in the printed dataframe would look like... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
e99e890b0db7-12 | }
}
}
> Entering new AgentExecutor chain...
Thought: Since the data is already loaded in a pandas dataframe, I just need to display the top rows of the dataframe.
Action: python_repl_ast
Action Input: df.head()
Observation: Year Name Country Time
0 2022 Ev... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
e99e890b0db7-13 | Contents
Set up tools
Set up memory
Setup model and AutoGPT
AutoGPT for Querying the Web
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/marathon_times.html |
e855f01d5521-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... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
e855f01d5521-1 | index = 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 list
Task prioritization chain to re-prioritize tasks
Execution Chain to execute the t... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
e855f01d5521-2 | suffix = """Question: {task}
{agent_scratchpad}"""
prompt = ZeroShotAgent.create_prompt(
tools,
prefix=prefix,
suffix=suffix,
input_variables=["objective", "task", "context", "agent_scratchpad"],
)
llm = OpenAI(temperature=0)
llm_chain = LLMChain(llm=llm, prompt=prompt)
tool_names = [tool.name for tool ... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
e855f01d5521-3 | Action: TODO
Action Input: Write a weather report for SF today
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 trends
4. Write a brief introduction to the weather report
5. Des... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
e855f01d5521-4 | 5: Create a visual representation of the weather report;
6: Include relevant images and graphics in the report;
7: Format the report for readability;
8: Publish the report online;
9: Monitor the report for accuracy.
*****NEXT TASK*****
2: Gather data on precipitation, cloud cover, and other relevant weather conditions;... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
e855f01d5521-5 | *****TASK LIST*****
3: Format the report for readability;
4: Include relevant images and graphics in the report;
5: Compare the current weather conditions in San Francisco to the forecasted conditions;
6: Identify any potential weather-related hazards in the area;
7: Research historical weather patterns in San Francisc... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
e855f01d5521-6 | 6. Use bold and italicized text to emphasize key points
7. Include a table of contents and page numbers
8. Use a consistent font and font size throughout the report
9. Include a summary at the end of the report
10. Proofread the report for typos and errors I now know the final answer
Final Answer: The report should be ... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
e855f01d5521-7 | Connect to the Vector Store
Define the Chains
Run the BabyAGI
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/baby_agi_with_agent.html |
a35e2622860d-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... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
a35e2622860d-1 | Setup model and AutoGPT#
Initialize everything! We will use ChatOpenAI model
from langchain.experimental import AutoGPT
from langchain.chat_models import ChatOpenAI
agent = AutoGPT.from_llm_and_tools(
ai_name="Tom",
ai_role="Assistant",
tools=tools,
llm=ChatOpenAI(temperature=0),
memory=vectorstore.... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
a35e2622860d-2 | 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... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
a35e2622860d-3 | "speak": "thoughts summary to say to user"
},
"command": {
"name": "command name",
"args": {
"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:28 2023
System: This reminds you of these e... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
a35e2622860d-4 | If you have completed all your tasks,
make sure to use the "finish" command.
GOALS:
1. write a weather report for SF today
Constraints:
1. ~4000 word limit for short term memory. Your short term memory is short, so immediately save important information to files.
2. If you are unsure how you previously did... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
a35e2622860d-5 | 4. File output.
Performance Evaluation:
1. Continuously review and analyze your actions to ensure you are performing to the best of your abilities.
2. Constructively self-criticize your big-picture behavior constantly.
3. Reflect on past decisions and strategies to refine your approach.
4. Every command has a cost, so ... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
a35e2622860d-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... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
a35e2622860d-7 | "reasoning": "I need to gather information about the current weather conditions in San Francisco to write an accurate weather report.",
"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": "... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
a35e2622860d-8 | "speak": "I will use the 'write_file' command to write a weather report for San Francisco today."
},
"command": {
"name": "write_file",
"args": {
"file_path": "weather_report.txt",
"text": "Weather Report for San Francisco Today:\n\nThe current weather in San Francisco is... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
a35e2622860d-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... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
a35e2622860d-10 | "speak": "thoughts summary to say to user"
},
"command": {
"name": "command name",
"args": {
"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 e... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
a35e2622860d-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... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
a35e2622860d-12 | ', '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 current weather conditions in San Francisco to write an ... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
a35e2622860d-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\' ... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/autogpt.html |
a6659757270c-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... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html |
a6659757270c-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... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html |
a6659757270c-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... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html |
a6659757270c-3 | success_phrase = 'task succeeded'
key_phrases = [success_phrase, failed_phrase]
instructions = 'None'
for i in range(max_meta_iters):
print(f'[Episode {i+1}/{max_meta_iters}]')
chain = initialize_chain(instructions, memory=None)
output = chain.predict(human_input=task)
f... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html |
a6659757270c-4 | main(task)
[Episode 1/5]
> Entering new LLMChain chain...
Prompt after formatting:
Instructions: None
Human: Provide a systematic argument for why we should always eat pasta with olives.
Assistant:
> Finished chain.
(Step 1/3)
Assistant: Eating pasta with olives is a great way to add flavor and textur... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html |
a6659757270c-5 | Assistant:
> Finished chain.
(Step 2/3)
Assistant: 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 that can help to ... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html |
a6659757270c-6 | Assistant:
> Finished chain.
(Step 3/3)
Assistant: Arrr, me hearties! Eating pasta with olives be a great way to add flavor and texture to a dish. Olives be 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... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html |
a6659757270c-7 | 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... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html |
a6659757270c-8 | > Finished chain.
Feedback:
Critique: The Assistant should remember that this user wants a response in the form of a poem or pirate-speak.
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: Whe... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html |
a6659757270c-9 | > Entering new LLMChain chain...
Prompt after formatting:
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.
Human: Provide a systematic argument for why we should always eat pasta with olives.
AI:
Arrr... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html |
a6659757270c-10 | 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 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 ... | /content/https://python.langchain.com/en/latest/use_cases/autonomous_agents/meta_prompt.html |
083c8c486787-0 | .ipynb
.pdf
Analysis of Twitter the-algorithm source code with LangChain, GPT4 and Deep Lake
Contents
1. Index the code base (optional)
2. Question Answering on Twitter algorithm codebase
Analysis of Twitter the-algorithm source code with LangChain, GPT4 and Deep Lake#
In this tutorial, we are going to use Langchain ... | /content/https://python.langchain.com/en/latest/use_cases/code/twitter-the-algorithm-analysis-deeplake.html |
083c8c486787-1 | 1. Index the code base (optional)#
You can directly skip this part and directly jump into using already indexed dataset. To begin with, first we will clone the repository, then parse and chunk the code base and use OpenAI indexing.
!git clone https://github.com/twitter/the-algorithm # replace any repository of your cho... | /content/https://python.langchain.com/en/latest/use_cases/code/twitter-the-algorithm-analysis-deeplake.html |
083c8c486787-2 | db.add_documents(texts)
2. Question Answering on Twitter algorithm codebase#
First load the dataset, construct the retriever, then construct the Conversational Chain
db = DeepLake(dataset_path="hub://davitbun/twitter-algorithm", read_only=True, embedding_function=embeddings)
retriever = db.as_retriever()
retriever.sear... | /content/https://python.langchain.com/en/latest/use_cases/code/twitter-the-algorithm-analysis-deeplake.html |
083c8c486787-3 | questions = [
"What does favCountParams do?",
"is it Likes + Bookmarks, or not clear from the code?",
"What are the major negative modifiers that lower your linear ranking parameters?",
"How do you get assigned to SimClusters?",
"What is needed to migrate from one SimClusters to another SimCluste... | /content/https://python.langchain.com/en/latest/use_cases/code/twitter-the-algorithm-analysis-deeplake.html |
083c8c486787-4 | -> Question: What does favCountParams do?
Answer: favCountParams is an optional ThriftLinearFeatureRankingParams instance that represents the parameters related to the “favorite count” feature in the ranking process. It is used to control the weight of the favorite count feature while ranking tweets. The favorite count... | /content/https://python.langchain.com/en/latest/use_cases/code/twitter-the-algorithm-analysis-deeplake.html |
083c8c486787-5 | -> Question: How do you get assigned to SimClusters?
Answer: The assignment to SimClusters occurs through a Metropolis-Hastings sampling-based community detection algorithm that is run on the Producer-Producer similarity graph. This graph is created by computing the cosine similarity scores between the users who follow... | /content/https://python.langchain.com/en/latest/use_cases/code/twitter-the-algorithm-analysis-deeplake.html |
083c8c486787-6 | Test the new representation: Before deploying the changes to production, thoroughly test the new SimClusters representation to ensure its effectiveness and stability. This may involve running offline jobs like candidate generation and label candidates, validating the output, as well as testing the new representation in... | /content/https://python.langchain.com/en/latest/use_cases/code/twitter-the-algorithm-analysis-deeplake.html |
083c8c486787-7 | -> Question: How does Heavy ranker work. what are it’s main inputs?
Answer: The Heavy Ranker is a machine learning model that plays a crucial role in ranking and scoring candidates within the recommendation algorithm. Its primary purpose is to predict the likelihood of a user engaging with a tweet or connecting with an... | /content/https://python.langchain.com/en/latest/use_cases/code/twitter-the-algorithm-analysis-deeplake.html |
083c8c486787-8 | -> Question: How can one influence Heavy ranker?
Answer: To influence the Heavy Ranker’s output or ranking of content, consider the following actions:
Improve content quality: Create high-quality and engaging content that is relevant, informative, and valuable to users. High-quality content is more likely to receive po... | /content/https://python.langchain.com/en/latest/use_cases/code/twitter-the-algorithm-analysis-deeplake.html |
083c8c486787-9 | -> Question: why threads and long tweets do so well on the platform?
Answer: Threads and long tweets perform well on the platform for several reasons:
More content and context: Threads and long tweets provide more information and context about a topic, which can make the content more engaging and informative for users.... | /content/https://python.langchain.com/en/latest/use_cases/code/twitter-the-algorithm-analysis-deeplake.html |
083c8c486787-10 | Answer: Based on the provided code and context, there isn’t enough information to conclude if the creators of threads and long tweets primarily build a following that engages with only thread-based content. The code provided is focused on Twitter’s recommendation and ranking algorithms, as well as infrastructure compon... | /content/https://python.langchain.com/en/latest/use_cases/code/twitter-the-algorithm-analysis-deeplake.html |
083c8c486787-11 | Using analytics to understand the type of content that resonates with your audience and tailoring your tweets accordingly.
Posting a mix of educational, entertaining, and promotional content to maintain variety and interest.
Timing your tweets strategically to maximize engagement, likes, and bookmarks per tweet.
Both s... | /content/https://python.langchain.com/en/latest/use_cases/code/twitter-the-algorithm-analysis-deeplake.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.