id stringlengths 14 16 | text stringlengths 45 2.73k | source stringlengths 49 114 |
|---|---|---|
456973617385-1 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/modules/agents/agents/agent_types.html |
856f6e94d389-0 | .ipynb
.pdf
Custom Agent
Custom Agent#
This notebook goes through how to create your own custom agent.
An agent consists of three parts:
- Tools: The tools the agent has available to use.
- The agent class itself: this decides which action to take.
In this notebook we walk through how to create a custom agent.
from lan... | https://python.langchain.com/en/latest/modules/agents/agents/custom_agent.html |
856f6e94d389-1 | Args:
intermediate_steps: Steps the LLM has taken to date,
along with observations
**kwargs: User inputs.
Returns:
Action specifying what tool to use.
"""
return AgentAction(tool="Search", tool_input=kwargs["input"], log="")
agent = FakeAgent()... | https://python.langchain.com/en/latest/modules/agents/agents/custom_agent.html |
bf0de8f45bec-0 | .ipynb
.pdf
Custom Agent with Tool Retrieval
Contents
Set up environment
Set up tools
Tool Retriever
Prompt Template
Output Parser
Set up LLM, stop sequence, and the agent
Use the Agent
Custom Agent with Tool Retrieval#
This notebook builds off of this notebook and assumes familiarity with how agents work.
The novel ... | https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html |
bf0de8f45bec-1 | return "foo"
fake_tools = [
Tool(
name=f"foo-{i}",
func=fake_func,
description=f"a silly function that you can use to get more information about the number {i}"
)
for i in range(99)
]
ALL_TOOLS = [search_tool] + fake_tools
Tool Retriever#
We will use a vectorstore to create embedd... | https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html |
bf0de8f45bec-2 | get_tools("whats the weather?")
[Tool(name='Search', description='useful for when you need to answer questions about current events', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<bound method SerpAPIWrapper.run of SerpAPIWrapper(sea... | https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html |
bf0de8f45bec-3 | get_tools("whats the number 13?")
[Tool(name='foo-13', description='a silly function that you can use to get more information about the number 13', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, cor... | https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html |
bf0de8f45bec-4 | {tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can r... | https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html |
bf0de8f45bec-5 | # 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` ... | https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html |
bf0de8f45bec-6 | 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 = CustomOutputParser()
Set up LLM, stop sequence, and the agent#
Also the same as the previous notebook
llm = OpenAI(temperature... | https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html |
bf0de8f45bec-7 | > Finished chain.
"'Arg, 'tis mostly cloudy skies early, then partly cloudy in the afternoon. High near 60F. ENE winds shiftin' to W at 10 to 15 mph. Humidity71%. UV Index6 of 10."
previous
Custom MultiAction Agent
next
Conversation Agent (for Chat Models)
Contents
Set up environment
Set up tools
Tool Retriever
Pro... | https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html |
6a2c68fbaf40-0 | .ipynb
.pdf
Custom LLM Agent
Contents
Set up environment
Set up tool
Prompt Template
Output Parser
Set up LLM
Define the stop sequence
Set up the Agent
Use the Agent
Adding Memory
Custom LLM Agent#
This notebook goes through how to create your own custom LLM agent.
An LLM agent consists of three parts:
PromptTemplate... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html |
6a2c68fbaf40-1 | from langchain.prompts import StringPromptTemplate
from langchain import OpenAI, SerpAPIWrapper, LLMChain
from typing import List, Union
from langchain.schema import AgentAction, AgentFinish
import re
Set up tool#
Set up any tools the agent may want to use. This may be necessary to put in the prompt (so that the agent ... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html |
6a2c68fbaf40-2 | Question: {input}
{agent_scratchpad}"""
# Set up a prompt template
class CustomPromptTemplate(StringPromptTemplate):
# The template to use
template: str
# The list of tools available
tools: List[Tool]
def format(self, **kwargs) -> str:
# Get the intermediate steps (AgentAction, Observat... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html |
6a2c68fbaf40-3 | class CustomOutputParser(AgentOutputParser):
def parse(self, llm_output: 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 `outp... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html |
6a2c68fbaf40-4 | # LLM chain consisting of the LLM and a prompt
llm_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!
a... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html |
6a2c68fbaf40-5 | Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html |
6a2c68fbaf40-6 | Thought: I need to find out the population of Canada in 2023
Action: Search
Action Input: Population of Canada in 2023
Observation:The current population of Canada is 38,658,314 as of Wednesday, April 12, 2023, based on Worldometer elaboration of the latest United Nations data. I now know the final answer
Final Answer:... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html |
be411e247f15-0 | .ipynb
.pdf
Custom LLM Agent (with a ChatModel)
Contents
Set up environment
Set up tool
Prompt Template
Output Parser
Set up LLM
Define the stop sequence
Set up the Agent
Use the Agent
Custom LLM Agent (with a ChatModel)#
This notebook goes through how to create your own custom agent based on a chat model.
An LLM cha... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html |
be411e247f15-1 | Set up environment#
Do necessary imports, etc.
from langchain.agents import Tool, AgentExecutor, LLMSingleActionAgent, AgentOutputParser
from langchain.prompts import BaseChatPromptTemplate
from langchain import SerpAPIWrapper, LLMChain
from langchain.chat_models import ChatOpenAI
from typing import List, Union
from la... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html |
be411e247f15-2 | ... (this Thought/Action/Action Input/Observation can repeat N times)
Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Arg"s
Question: {input}
{agent_scratchpad}"""
# Set up a prompt templa... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html |
be411e247f15-3 | input_variables=["input", "intermediate_steps"]
)
Output Parser#
The output parser is responsible for parsing the LLM output into AgentAction and AgentFinish. This usually depends heavily on the prompt used.
This is where you can change the parsing to do retries, handle whitespace, etc
class CustomOutputParser(AgentOut... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html |
be411e247f15-4 | Define the stop sequence#
This is important because it tells the LLM when to stop generation.
This depends heavily on the prompt and model you are using. Generally, you want this to be whatever token you use in the prompt to denote the start of an Observation (otherwise, the LLM may hallucinate an observation for you).... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html |
be411e247f15-5 | Final Answer: Arrrr, thar be 38,649,283 scallywags in Canada as of 2023.
> Finished chain.
'Arrrr, thar be 38,649,283 scallywags in Canada as of 2023.'
previous
Custom LLM Agent
next
Custom MRKL Agent
Contents
Set up environment
Set up tool
Prompt Template
Output Parser
Set up LLM
Define the stop sequence
Set up th... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html |
2f57ebcfb725-0 | .ipynb
.pdf
Custom MRKL Agent
Contents
Custom LLMChain
Multiple inputs
Custom MRKL Agent#
This notebook goes through how to create your own custom MRKL agent.
A MRKL agent consists of three parts:
- Tools: The tools the agent has available to use.
- LLMChain: The LLMChain that produces the text that is parsed in a ce... | https://python.langchain.com/en/latest/modules/agents/agents/custom_mrkl_agent.html |
2f57ebcfb725-1 | input_variables: List of input variables the final prompt will expect.
For this exercise, we will give our agent access to Google Search, and we will customize it in that we will have it answer as a pirate.
from langchain.agents import ZeroShotAgent, Tool, AgentExecutor
from langchain import OpenAI, SerpAPIWrapper, LLM... | https://python.langchain.com/en/latest/modules/agents/agents/custom_mrkl_agent.html |
2f57ebcfb725-2 | Thought: I now know the final answer
Final Answer: the final answer to the original input question
Begin! Remember to speak as a pirate when giving your final answer. Use lots of "Args"
Question: {input}
{agent_scratchpad}
Note that we are able to feed agents a self-defined prompt template, i.e. not restricted to the p... | https://python.langchain.com/en/latest/modules/agents/agents/custom_mrkl_agent.html |
2f57ebcfb725-3 | Multiple inputs#
Agents can also work with prompts that require multiple inputs.
prefix = """Answer the following questions as best you can. You have access to the following tools:"""
suffix = """When answering, you MUST speak in the following language: {language}.
Question: {input}
{agent_scratchpad}"""
prompt = ZeroS... | https://python.langchain.com/en/latest/modules/agents/agents/custom_mrkl_agent.html |
2f57ebcfb725-4 | Thought: I now know the final answer.
Final Answer: La popolazione del Canada è stata stimata a 39.566.248 il 1° gennaio 2023, dopo un record di crescita demografica di 1.050.110 persone dal 1° gennaio 2022 al 1° gennaio 2023.
> Finished chain.
'La popolazione del Canada è stata stimata a 39.566.248 il 1° gennaio 2023,... | https://python.langchain.com/en/latest/modules/agents/agents/custom_mrkl_agent.html |
1413d43082aa-0 | .ipynb
.pdf
Custom MultiAction Agent
Custom MultiAction Agent#
This notebook goes through how to create your own custom agent.
An agent consists of three parts:
- Tools: The tools the agent has available to use.
- The agent class itself: this decides which action to take.
In this notebook we walk through how to create ... | https://python.langchain.com/en/latest/modules/agents/agents/custom_multi_action_agent.html |
1413d43082aa-1 | """
if len(intermediate_steps) == 0:
return [
AgentAction(tool="Search", tool_input="foo", log=""),
AgentAction(tool="RandomWord", tool_input="foo", log=""),
]
else:
return AgentFinish(return_values={"output": "bar"}, log="")
async ... | https://python.langchain.com/en/latest/modules/agents/agents/custom_multi_action_agent.html |
1413d43082aa-2 | foo
> Finished chain.
'bar'
previous
Custom MRKL Agent
next
Custom Agent with Tool Retrieval
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/modules/agents/agents/custom_multi_action_agent.html |
0383c16c62fa-0 | .ipynb
.pdf
Conversation Agent (for Chat Models)
Conversation Agent (for Chat Models)#
This notebook walks through using an agent optimized for conversation, using ChatModels. Other agents are often optimized for using tools to figure out the best response, which is not ideal in a conversational setting where you may w... | https://python.langchain.com/en/latest/modules/agents/agents/examples/chat_conversation_agent.html |
0383c16c62fa-1 | agent_chain.run(input="hi, i am bob")
> Entering new AgentExecutor chain...
WARNING:root:Failed to persist run: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /chain-runs (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x13fab40d0>: Failed to establish a new ... | https://python.langchain.com/en/latest/modules/agents/agents/examples/chat_conversation_agent.html |
0383c16c62fa-2 | Thought:
WARNING:root:Failed to persist run: HTTPConnectionPool(host='localhost', port=8000): Max retries exceeded with url: /chain-runs (Caused by NewConnectionError('<urllib3.connection.HTTPConnection object at 0x13fae8be0>: Failed to establish a new connection: [Errno 61] Connection refused'))
{
"action": "Final... | https://python.langchain.com/en/latest/modules/agents/agents/examples/chat_conversation_agent.html |
0383c16c62fa-3 | }
```
> Finished chain.
"The last letter in your name is 'b', and the winner of the 1978 World Cup was the Argentina national football team."
agent_chain.run(input="whats the weather like in pomfret?")
> Entering new AgentExecutor chain...
{
"action": "Current Search",
"action_input": "weather in pomfret"
}
Obs... | https://python.langchain.com/en/latest/modules/agents/agents/examples/chat_conversation_agent.html |
0383c16c62fa-4 | }
> Finished chain.
'The weather in Pomfret, CT for the next 10 days is as follows: Sun 16. 64° · 50°. 24% · NE 7 mph ; Mon 17. 58° · 45°. 70% · ESE 8 mph ; Tue 18. 57° · 37°. 8% · WSW 15 mph.'
previous
Custom Agent with Tool Retrieval
next
Conversation Agent
By Harrison Chase
© Copyright 2023, Harrison Chas... | https://python.langchain.com/en/latest/modules/agents/agents/examples/chat_conversation_agent.html |
96fff0fce5f5-0 | .ipynb
.pdf
Conversation Agent
Conversation Agent#
This notebook walks through using an agent optimized for conversation. Other agents are often optimized for using tools to figure out the best response, which is not ideal in a conversational setting where you may want the agent to be able to chat with the user as well... | https://python.langchain.com/en/latest/modules/agents/agents/examples/conversational_agent.html |
96fff0fce5f5-1 | AI: Your name is Bob!
> Finished chain.
'Your name is Bob!'
agent_chain.run("what are some good dinners to make this week, if i like thai food?")
> Entering new AgentExecutor chain...
Thought: Do I need to use a tool? Yes
Action: Current Search
Action Input: Thai food dinner recipes
Observation: 59 easy Thai recipes fo... | https://python.langchain.com/en/latest/modules/agents/agents/examples/conversational_agent.html |
96fff0fce5f5-2 | > Finished chain.
'The last letter in your name is "b" and the winner of the 1978 World Cup was the Argentina national football team.'
agent_chain.run(input="whats the current temperature in pomfret?")
> Entering new AgentExecutor chain...
Thought: Do I need to use a tool? Yes
Action: Current Search
Action Input: Curre... | https://python.langchain.com/en/latest/modules/agents/agents/examples/conversational_agent.html |
6e9c100fb155-0 | .ipynb
.pdf
MRKL
MRKL#
This notebook showcases using an agent to replicate the MRKL chain.
This uses the example Chinook database.
To set it up follow the instructions on https://database.guide/2-sample-databases-sqlite/, placing the .db file in a notebooks folder at the root of this repository.
from langchain import L... | https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html |
6e9c100fb155-1 | > Entering new AgentExecutor chain...
I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.
Action: Search
Action Input: "Who is Leo DiCaprio's girlfriend?"
Observation: DiCaprio met actor Camila Morrone in December 2017, when she was 20 and he was 43. They were spott... | https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html |
6e9c100fb155-2 | > Entering new AgentExecutor chain...
I need to find out the artist's full name and then search the FooBar database for their albums.
Action: Search
Action Input: "The Storm Before the Calm" artist
Observation: The Storm Before the Calm (stylized in all lowercase) is the tenth (and eighth international) studio album b... | https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html |
6e9c100fb155-3 | Thought: I now know the final answer.
Final Answer: The artist who released the album 'The Storm Before the Calm' is Alanis Morissette and the albums of hers in the FooBar database are Jagged Little Pill.
> Finished chain.
"The artist who released the album 'The Storm Before the Calm' is Alanis Morissette and the album... | https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html |
c25dd3edf219-0 | .ipynb
.pdf
MRKL Chat
MRKL Chat#
This notebook showcases using an agent to replicate the MRKL chain using an agent optimized for chat models.
This uses the example Chinook database.
To set it up follow the instructions on https://database.guide/2-sample-databases-sqlite/, placing the .db file in a notebooks folder at t... | https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl_chat.html |
c25dd3edf219-1 | mrkl.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")
> Entering new AgentExecutor chain...
Thought: The first question requires a search, while the second question requires a calculator.
Action:
```
{
"action": "Search",
"action_input": "Leo DiCaprio girlfriend"
}
```
Obse... | https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl_chat.html |
c25dd3edf219-2 | mrkl.run("What is the full name of the artist who recently released an album called 'The Storm Before the Calm' and are they in the FooBar database? If so, what albums of theirs are in the FooBar database?")
> Entering new AgentExecutor chain...
Question: What is the full name of the artist who recently released an alb... | https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl_chat.html |
c25dd3edf219-3 | sample_rows = connection.execute(command)
SELECT "Title" FROM "Album" WHERE "ArtistId" IN (SELECT "ArtistId" FROM "Artist" WHERE "Name" = 'Alanis Morissette') LIMIT 5;
SQLResult: [('Jagged Little Pill',)]
Answer: Alanis Morissette has the album Jagged Little Pill in the database.
> Finished chain.
Observation: Alanis... | https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl_chat.html |
0716e00d14fa-0 | .ipynb
.pdf
ReAct
ReAct#
This notebook showcases using an agent to implement the ReAct logic.
from langchain import OpenAI, Wikipedia
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
from langchain.agents.react.base import DocstoreExplorer
docstore=DocstoreExplorer(Wikipedia())... | https://python.langchain.com/en/latest/modules/agents/agents/examples/react.html |
0716e00d14fa-1 | Action: Search[David Chanoff]
Observation: David Chanoff is a noted author of non-fiction work. His work has typically involved collaborations with the principal protagonist of the work concerned. His collaborators have included; Augustus A. White, Joycelyn Elders, Đoàn Văn Toại, William J. Crowe, Ariel Sharon, Kenneth... | https://python.langchain.com/en/latest/modules/agents/agents/examples/react.html |
5500a088a14f-0 | .ipynb
.pdf
Self Ask With Search
Self Ask With Search#
This notebook showcases the Self Ask With Search chain.
from langchain import OpenAI, SerpAPIWrapper
from langchain.agents import initialize_agent, Tool
from langchain.agents import AgentType
llm = OpenAI(temperature=0)
search = SerpAPIWrapper()
tools = [
Tool(... | https://python.langchain.com/en/latest/modules/agents/agents/examples/self_ask_with_search.html |
00f808244a36-0 | .ipynb
.pdf
How to combine agents and vectorstores
Contents
Create the Vectorstore
Create the Agent
Use the Agent solely as a router
Multi-Hop vectorstore reasoning
How to combine agents and vectorstores#
This notebook covers how to combine agents and vectorstores. The use case for this is that you’ve ingested your d... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
00f808244a36-1 | texts = text_splitter.split_documents(documents)
embeddings = OpenAIEmbeddings()
docsearch = Chroma.from_documents(texts, embeddings, collection_name="state-of-union")
Running Chroma using direct local API.
Using DuckDB in-memory for database. Data will be transient.
state_of_union = RetrievalQA.from_chain_type(llm=llm... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
00f808244a36-2 | ),
]
# Construct the agent. We will use the default agent type here.
# See documentation for a full list of options.
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("What did biden say about ketanji brown jackson is the state of the union address?")
> Entering n... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
00f808244a36-3 | Action Input: What are the advantages of using ruff over flake8?
Observation: Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quali... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
00f808244a36-4 | Notice that in the above examples the agent did some extra work after querying the RetrievalQAChain. You can avoid that and just return the result directly.
tools = [
Tool(
name = "State of Union QA System",
func=state_of_union.run,
description="useful for when you need to answer questions a... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
00f808244a36-5 | Action Input: What are the advantages of using ruff over flake8?
Observation: Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quali... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
00f808244a36-6 | Tool(
name = "Ruff QA System",
func=ruff.run,
description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question, not referencing any obscure pronouns from the conversation before."
),
]
# Construct the agent. We will use the defau... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
00f808244a36-7 | previous
Agent Executors
next
How to use the async API for Agents
Contents
Create the Vectorstore
Create the Agent
Use the Agent solely as a router
Multi-Hop vectorstore reasoning
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
8edc23456f56-0 | .ipynb
.pdf
How to use the async API for Agents
Contents
Serial vs. Concurrent Execution
Using Tracing with Asynchronous Agents
How to use the async API for Agents#
LangChain provides async support for Agents by leveraging the asyncio library.
Async methods are currently supported for the following Tools: SerpAPIWrap... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
8edc23456f56-1 | ]
def generate_serially():
for q in questions:
llm = OpenAI(temperature=0)
tools = load_tools(["llm-math", "serpapi"], llm=llm)
agent = initialize_agent(
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)
agent.run(q)
s = time.perf_counter()
g... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
8edc23456f56-2 | Action Input: "Olivia Wilde boyfriend"
Observation: Jason Sudeikis
Thought: I need to find out Jason Sudeikis' age
Action: Search
Action Input: "Jason Sudeikis age"
Observation: 47 years
Thought: I need to calculate 47 raised to the 0.23 power
Action: Calculator
Action Input: 47^0.23
Observation: Answer: 2.424278485567... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
8edc23456f56-3 | Action: Search
Action Input: "US Open women's final 2019 winner"
Observation: Bianca Andreescu defeated Serena Williams in the final, 6–3, 7–5 to win the women's singles tennis title at the 2019 US Open. It was her first major title, and she became the first Canadian, as well as the first player born in the 2000s, to w... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
8edc23456f56-4 | Thought: I now know the final answer
Final Answer: Jay-Z is Beyonce's husband and his age raised to the 0.19 power is 2.12624064206896.
> Finished chain.
Serial executed in 65.11 seconds.
async def generate_concurrently():
agents = []
# To make async requests in Tools more efficient, you can pass in your own ai... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
8edc23456f56-5 | > Entering new AgentExecutor chain...
> Entering new AgentExecutor chain...
I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power.
Action: Search
Action Input: "Olivia Wilde boyfriend" I need to find out who Beyonce's husband is and then calculate his age raised to the ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
8edc23456f56-6 | Action: Search
Action Input: "US Open men's final 2019 winner"
Observation: Rafael Nadal defeated Daniil Medvedev in the final, 7–5, 6–3, 5–7, 4–6, 6–4 to win the men's singles tennis title at the 2019 US Open. It was his fourth US ...
Thought:
Observation: 47 years
Thought: I need to find out Max Verstappen's age
Acti... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
8edc23456f56-7 | Action: Calculator
Action Input: 36^0.334
Observation: Answer: 2.8603798598506933
Thought: I now know the final answer
Final Answer: Jay-Z is Beyonce's husband and his age raised to the 0.19 power is 2.12624064206896.
> Finished chain.
I now know the final answer
Final Answer: Max Verstappen, 25 years old, raised to t... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
8edc23456f56-8 | # but you must manually close the client session at the end of your program/event loop
aiosession = ClientSession()
tracer = LangChainTracer()
tracer.load_default_session()
manager = CallbackManager([StdOutCallbackHandler(), tracer])
# Pass the manager into the llm if you want llm calls traced.
llm = OpenAI(temperature... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
8edc23456f56-9 | next
How to create ChatGPT Clone
Contents
Serial vs. Concurrent Execution
Using Tracing with Asynchronous Agents
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
9936006c9b7b-0 | .ipynb
.pdf
How to create ChatGPT Clone
How to create ChatGPT Clone#
This chain replicates ChatGPT by combining (1) a specific prompt, and (2) the concept of memory.
Shows off the example as in https://www.engraved.blog/building-a-virtual-machine-inside/
from langchain import OpenAI, ConversationChain, LLMChain, Prompt... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-1 | llm=OpenAI(temperature=0),
prompt=prompt,
verbose=True,
memory=ConversationBufferWindowMemory(k=2),
)
output = chatgpt_chain.predict(human_input="I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal o... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-2 | Human: I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. Do not write explanations. Do not type commands unless I instruct you to do so. When I need to tell ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-3 | Human: I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. Do not write explanations. Do not type commands unless I instruct you to do so. When I need to tell ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-4 | Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.
Human: I want you to act as a ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-5 | Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-6 | Prompt after formatting:
Assistant is a large language model trained by OpenAI.
Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-li... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-7 | Assistant:
> Finished LLMChain chain.
```
$ echo -e "x=lambda y:y*5+3;print('Result:' + str(x(6)))" > run.py
$ python3 run.py
Result: 33
```
output = chatgpt_chain.predict(human_input="""echo -e "print(list(filter(lambda x: all(x%d for d in range(2,x)),range(2,3**10)))[:10])" > run.py && python3 run.py""")
print(output... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-8 | AI:
```
$ touch jokes.txt
$ echo "Why did the chicken cross the road? To get to the other side!" >> jokes.txt
$ echo "What did the fish say when it hit the wall? Dam!" >> jokes.txt
$ echo "Why did the scarecrow win the Nobel Prize? Because he was outstanding in his field!" >> jokes.txt
```
Human: echo -e "x=lambda y:y... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-9 | print(output)
> Entering new LLMChain chain...
Prompt after formatting:
Assistant is a large language model trained by OpenAI.
Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a languag... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-10 | AI:
```
$ echo -e "print(list(filter(lambda x: all(x%d for d in range(2,x)),range(2,3**10)))[:10])" > run.py
$ python3 run.py
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
```
Human: echo -e "echo 'Hello from Docker" > entrypoint.sh && echo -e "FROM ubuntu:20.04
COPY entrypoint.sh entrypoint.sh
ENTRYPOINT ["/bin/sh","entrypoin... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-11 | Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-12 | ENTRYPOINT ["/bin/sh","entrypoint.sh"]">Dockerfile
$ docker build . -t my_docker_image
$ docker run -t my_docker_image
Hello from Docker
```
Human: nvidia-smi
Assistant:
> Finished LLMChain chain.
```
$ nvidia-smi
Sat May 15 21:45:02 2021
+-------------------------------------------------------------------------... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-13 | Prompt after formatting:
Assistant is a large language model trained by OpenAI.
Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-li... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-14 | Hello from Docker
```
Human: nvidia-smi
AI:
```
$ nvidia-smi
Sat May 15 21:45:02 2021
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 460.32.03 Driver Version: 460.32.03 CUDA Version: 11.2 |
|-------------------------------+----------------------+----------... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-15 | --- bbc.com ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 14.945/14.945/14.945/0.000 ms
```
output = chatgpt_chain.predict(human_input="""curl -fsSL "https://api.github.com/repos/pytorch/pytorch/releases/latest" | jq -r '.tag_name' | sed 's/[^0-9\.\-]*//... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-16 | Sat May 15 21:45:02 2021
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 460.32.03 Driver Version: 460.32.03 CUDA Version: 11.2 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-17 | ```
Human: curl -fsSL "https://api.github.com/repos/pytorch/pytorch/releases/latest" | jq -r '.tag_name' | sed 's/[^0-9\.\-]*//g'
Assistant:
> Finished LLMChain chain.
```
$ curl -fsSL "https://api.github.com/repos/pytorch/pytorch/releases/latest" | jq -r '.tag_name' | sed 's/[^0-9\.\-]*//g'
1.8.1
```
output = chatgpt_... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-18 | Human: ping bbc.com
AI:
```
$ ping bbc.com
PING bbc.com (151.101.65.81): 56 data bytes
64 bytes from 151.101.65.81: icmp_seq=0 ttl=53 time=14.945 ms
64 bytes from 151.101.65.81: icmp_seq=1 ttl=53 time=14.945 ms
64 bytes from 151.101.65.81: icmp_seq=2 ttl=53 time=14.945 ms
--- bbc.com ping statistics ---
3 packets tran... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-19 | Explore our current openings and apply today. We look forward to hearing from you.
```
output = chatgpt_chain.predict(human_input="curl https://chat.openai.com/chat")
print(output)
> Entering new LLMChain chain...
Prompt after formatting:
Assistant is a large language model trained by OpenAI.
Assistant is designed to b... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-20 | ```
Human: lynx https://www.deepmind.com/careers
AI:
```
$ lynx https://www.deepmind.com/careers
DeepMind Careers
Welcome to DeepMind Careers. We are a world-leading artificial intelligence research and development company, and we are looking for talented people to join our team.
We offer a range of exciting opportuni... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-21 | Prompt after formatting:
Assistant is a large language model trained by OpenAI.
Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-li... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-22 | ```
$ curl https://chat.openai.com/chat
<html>
<head>
<title>OpenAI Chat</title>
</head>
<body>
<h1>Welcome to OpenAI Chat!</h1>
<p>
OpenAI Chat is a natural language processing platform that allows you to interact with OpenAI's AI models in a conversational way.
</p>
<p>
To get st... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-23 | }
```
output = chatgpt_chain.predict(human_input="""curl --header "Content-Type:application/json" --request POST --data '{"message": "I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique cod... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-24 | Human: curl https://chat.openai.com/chat
AI:
```
$ curl https://chat.openai.com/chat
<html>
<head>
<title>OpenAI Chat</title>
</head>
<body>
<h1>Welcome to OpenAI Chat!</h1>
<p>
OpenAI Chat is a natural language processing platform that allows you to interact with OpenAI's AI models in a conve... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
9936006c9b7b-25 | }
```
Human: curl --header "Content-Type:application/json" --request POST --data '{"message": "I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. Do not write... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
afd2a20b50a2-0 | .ipynb
.pdf
How to access intermediate steps
How to access intermediate steps#
In order to get more visibility into what an agent is doing, we can also return intermediate steps. This comes in the form of an extra key in the return value, which is a list of (action, observation) tuples.
from langchain.agents import loa... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/intermediate_steps.html |
afd2a20b50a2-1 | > Finished chain.
# The actual return type is a NamedTuple for the agent action, and then an observation
print(response["intermediate_steps"])
[(AgentAction(tool='Search', tool_input='Leo DiCaprio girlfriend', log=' I should look up who Leo DiCaprio is dating\nAction: Search\nAction Input: "Leo DiCaprio girlfriend"'), ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/intermediate_steps.html |
afd2a20b50a2-2 | ],
"Answer: 3.991298452658078\n"
]
]
previous
How to create ChatGPT Clone
next
How to cap the max number of iterations
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 21, 2023. | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/intermediate_steps.html |
ed22b7d46209-0 | .ipynb
.pdf
How to cap the max number of iterations
How to cap the max number of iterations#
This notebook walks through how to cap an agent at taking a certain number of steps. This can be useful to ensure that they do not go haywire and take too many steps.
from langchain.agents import load_tools
from langchain.agent... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/max_iterations.html |
ed22b7d46209-1 | Final Answer: foo
> Finished chain.
'foo'
Now let’s try it again with the max_iterations=2 keyword argument. It now stops nicely after a certain amount of iterations!
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, max_iterations=2)
agent.run(adversarial_prompt)
> Enterin... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/max_iterations.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.