id stringlengths 14 16 | source stringlengths 49 117 | text stringlengths 16 2.73k |
|---|---|---|
b856f60ef47c-7 | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html | 'The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data.'
agent_without_memory.run("what is their national anthem called?")
> Entering new AgentExecutor chain...
Thought: I should look up the answer
Action: Search
Action Input... |
b856f60ef47c-8 | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html | Observation: Most nation states have an anthem, defined as "a song, as of praise, devotion, or patriotism"; most anthems are either marches or hymns in style. List of all countries around the world with its national anthem. ... Title and lyrics in the language of the country and translated into English, Aug 1, 2021 ...... |
b856f60ef47c-9 | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html | Final Answer: The national anthem of [country] is [name of anthem].
> Finished AgentExecutor chain.
'The national anthem of [country] is [name of anthem].'
previous
How to add memory to a Multi-Input Chain
next
Adding Message Memory backed by a database to an Agent
By Harrison Chase
© Copyright 2023, Harriso... |
1994743a508a-0 | https://python.langchain.com/en/latest/modules/memory/examples/postgres_chat_message_history.html | .ipynb
.pdf
Postgres Chat Message History
Postgres Chat Message History#
This notebook goes over how to use Postgres to store chat message history.
from langchain.memory import PostgresChatMessageHistory
history = PostgresChatMessageHistory(connection_string="postgresql://postgres:mypassword@localhost/chat_history", se... |
5d05c4c11ba0-0 | https://python.langchain.com/en/latest/modules/memory/examples/entity_memory_with_sqlite.html | .ipynb
.pdf
Entity Memory with SQLite storage
Entity Memory with SQLite storage#
In this walkthrough we’ll create a simple conversation chain which uses ConversationEntityMemory backed by a SqliteEntityStore.
from langchain.chains import ConversationChain
from langchain.llms import OpenAI
from langchain.memory import C... |
5d05c4c11ba0-1 | https://python.langchain.com/en/latest/modules/memory/examples/entity_memory_with_sqlite.html | You are constantly learning and improving, and your capabilities are constantly evolving. You are 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. You have access to some personalized information provided by the ... |
1756e0da22c0-0 | https://python.langchain.com/en/latest/modules/memory/examples/cassandra_chat_message_history.html | .ipynb
.pdf
Cassandra Chat Message History
Cassandra Chat Message History#
This notebook goes over how to use Cassandra to store chat message history.
Cassandra is a distributed database that is well suited for storing large amounts of data.
It is a good choice for storing chat message history because it is easy to sca... |
017687c1eaad-0 | https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html | .ipynb
.pdf
How to create a custom Memory class
How to create a custom Memory class#
Although there are a few predefined types of memory in LangChain, it is highly possible you will want to add your own type of memory that is optimal for your application. This notebook covers how to do that.
For this notebook, we will ... |
017687c1eaad-1 | https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html | def load_memory_variables(self, inputs: Dict[str, Any]) -> Dict[str, str]:
"""Load the memory variables, in this case the entity key."""
# Get the input text and run through spacy
doc = nlp(inputs[list(inputs.keys())[0]])
# Extract known information about entities, if they exist.
... |
017687c1eaad-2 | https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html | And now we put it all together!
llm = OpenAI(temperature=0)
conversation = ConversationChain(llm=llm, prompt=prompt, verbose=True, memory=SpacyEntityMemory())
In the first example, with no prior knowledge about Harrison, the “Relevant entity information” section is empty.
conversation.predict(input="Harrison likes mach... |
017687c1eaad-3 | https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html | ' From what I know about Harrison, I believe his favorite subject in college was machine learning. He has expressed a strong interest in the subject and has mentioned it often.'
Again, please note that this implementation is pretty simple and brittle and probably not useful in a production setting. Its purpose is to sh... |
046067550594-0 | https://python.langchain.com/en/latest/modules/memory/examples/multiple_memory.html | .ipynb
.pdf
How to use multiple memory classes in the same chain
How to use multiple memory classes in the same chain#
It is also possible to use multiple memory classes in the same chain. To combine multiple memory classes, we can initialize the CombinedMemory class, and then use that.
from langchain.llms import OpenA... |
046067550594-1 | https://python.langchain.com/en/latest/modules/memory/examples/multiple_memory.html | Current conversation:
Human: Hi!
AI:
> Finished chain.
' Hi there! How can I help you?'
conversation.run("Can you tell me a joke?")
> Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific det... |
6ca52f79395c-0 | https://python.langchain.com/en/latest/modules/memory/examples/motorhead_memory.html | .ipynb
.pdf
Motörhead Memory
Contents
Setup
Motörhead Memory#
Motörhead is a memory server implemented in Rust. It automatically handles incremental summarization in the background and allows for stateless applications.
Setup#
See instructions at Motörhead for running the server locally.
from langchain.memory.motorhe... |
6ca52f79395c-1 | https://python.langchain.com/en/latest/modules/memory/examples/motorhead_memory.html | ' You said your name is Bob. Is that correct?'
llm_chain.run("whats for dinner?")
> Entering new LLMChain chain...
Prompt after formatting:
You are a chatbot having a conversation with a human.
Human: hi im bob
AI: Hi Bob, nice to meet you! How are you doing today?
Human: whats my name?
AI: You said your name is Bob.... |
ef67e05f06c1-0 | https://python.langchain.com/en/latest/modules/memory/examples/motorhead_memory_managed.html | .ipynb
.pdf
Motörhead Memory (Managed)
Contents
Setup
Motörhead Memory (Managed)#
Motörhead is a memory server implemented in Rust. It automatically handles incremental summarization in the background and allows for stateless applications.
Setup#
See instructions at Motörhead for running the managed version of Motorh... |
ef67e05f06c1-1 | https://python.langchain.com/en/latest/modules/memory/examples/motorhead_memory_managed.html | AI: Hi Bob, nice to meet you! How are you doing today?
Human: whats my name?
AI:
> Finished chain.
' You said your name is Bob. Is that correct?'
llm_chain.run("whats for dinner?")
> Entering new LLMChain chain...
Prompt after formatting:
You are a chatbot having a conversation with a human.
Human: hi im bob
AI: Hi B... |
b3b0643a0b6d-0 | https://python.langchain.com/en/latest/modules/memory/examples/redis_chat_message_history.html | .ipynb
.pdf
Redis Chat Message History
Redis Chat Message History#
This notebook goes over how to use Redis to store chat message history.
from langchain.memory import RedisChatMessageHistory
history = RedisChatMessageHistory("foo")
history.add_user_message("hi!")
history.add_ai_message("whats up?")
history.messages
[A... |
ee8b3f91cb6d-0 | https://python.langchain.com/en/latest/modules/memory/examples/mongodb_chat_message_history.html | .ipynb
.pdf
Mongodb Chat Message History
Mongodb Chat Message History#
This notebook goes over how to use Mongodb to store chat message history.
MongoDB is a source-available cross-platform document-oriented database program. Classified as a NoSQL database program, MongoDB uses JSON-like documents with optional schemas... |
30b1de2d0b34-0 | https://python.langchain.com/en/latest/modules/memory/examples/adding_memory.html | .ipynb
.pdf
How to add Memory to an LLMChain
How to add Memory to an LLMChain#
This notebook goes over how to use the Memory class with an LLMChain. For the purposes of this walkthrough, we will add the ConversationBufferMemory class, although this can be any memory class.
from langchain.memory import ConversationBuff... |
30b1de2d0b34-1 | https://python.langchain.com/en/latest/modules/memory/examples/adding_memory.html | Human: Not to bad - how are you?
Chatbot:
> Finished LLMChain chain.
" I'm doing great, thank you for asking!"
previous
VectorStore-Backed Memory
next
How to add memory to a Multi-Input Chain
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
5d81287e0dee-0 | https://python.langchain.com/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html | .ipynb
.pdf
How to add memory to a Multi-Input Chain
How to add memory to a Multi-Input Chain#
Most memory objects assume a single input. In this notebook, we go over how to add memory to a chain that has multiple inputs. As an example of such a chain, we will add memory to a question/answering chain. This chain takes ... |
5d81287e0dee-1 | https://python.langchain.com/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html | Chatbot:"""
prompt = PromptTemplate(
input_variables=["chat_history", "human_input", "context"],
template=template
)
memory = ConversationBufferMemory(memory_key="chat_history", input_key="human_input")
chain = load_qa_chain(OpenAI(temperature=0), chain_type="stuff", memory=memory, prompt=prompt)
query = "What... |
cffcd83d28a9-0 | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html | .ipynb
.pdf
Adding Message Memory backed by a database to an Agent
Adding Message Memory backed by a database to an Agent#
This notebook goes over adding memory to an Agent where the memory uses an external message store. Before going through this notebook, please walkthrough the following notebooks, as this will build... |
cffcd83d28a9-1 | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html | prompt = ZeroShotAgent.create_prompt(
tools,
prefix=prefix,
suffix=suffix,
input_variables=["input", "chat_history", "agent_scratchpad"]
)
Now we can create the ChatMessageHistory backed by the database.
message_history = RedisChatMessageHistory(url='redis://localhost:6379/0', ttl=600, session_id='my... |
cffcd83d28a9-2 | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html | Observation: The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data. · Canada ... Additional information related to Canadian population trends can be found on Statistics Canada's Population and Demography Portal. Population of... |
cffcd83d28a9-3 | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html | 'The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data.'
To test the memory of this agent, we can ask a followup question that relies on information in the previous exchange to be answered correctly.
agent_chain.run(input="wh... |
cffcd83d28a9-4 | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html | Observation: Jun 7, 2010 ... https://twitter.com/CanadaImmigrantCanadian National Anthem O Canada in HQ - complete with lyrics, captions, vocals & music.LYRICS:O Canada! Nov 23, 2022 ... After 100 years of tradition, O Canada was proclaimed Canada's national anthem in 1980. The music for O Canada was composed in 1880 b... |
cffcd83d28a9-5 | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html | Final Answer: The national anthem of Canada is called "O Canada".
> Finished AgentExecutor chain.
'The national anthem of Canada is called "O Canada".'
We can see that the agent remembered that the previous question was about Canada, and properly asked Google Search what the name of Canada’s national anthem was.
For fu... |
cffcd83d28a9-6 | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html | Observation: The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data. · Canada ... Additional information related to Canadian population trends can be found on Statistics Canada's Population and Demography Portal. Population of... |
cffcd83d28a9-7 | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html | 'The current population of Canada is 38,566,192 as of Saturday, December 31, 2022, based on Worldometer elaboration of the latest United Nations data.'
agent_without_memory.run("what is their national anthem called?")
> Entering new AgentExecutor chain...
Thought: I should look up the answer
Action: Search
Action Input... |
cffcd83d28a9-8 | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html | Observation: Most nation states have an anthem, defined as "a song, as of praise, devotion, or patriotism"; most anthems are either marches or hymns in style. List of all countries around the world with its national anthem. ... Title and lyrics in the language of the country and translated into English, Aug 1, 2021 ...... |
cffcd83d28a9-9 | https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html | Final Answer: The national anthem of [country] is [name of anthem].
> Finished AgentExecutor chain.
'The national anthem of [country] is [name of anthem].'
previous
How to add Memory to an Agent
next
Cassandra Chat Message History
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on J... |
d884149b85a6-0 | https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html | .ipynb
.pdf
How to customize conversational memory
Contents
AI Prefix
Human Prefix
How to customize conversational memory#
This notebook walks through a few ways to customize conversational memory.
from langchain.llms import OpenAI
from langchain.chains import ConversationChain
from langchain.memory import Conversati... |
d884149b85a6-1 | https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html | AI: Hi there! It's nice to meet you. How can I help you today?
Human: What's the weather?
AI:
> Finished ConversationChain chain.
' The current weather is sunny and warm with a temperature of 75 degrees Fahrenheit. The forecast for the next few days is sunny with temperatures in the mid-70s.'
# Now we can override it ... |
d884149b85a6-2 | https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html | The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
Human: Hi there!
AI Assistant: Hi there! It's nice to meet you. Ho... |
d884149b85a6-3 | https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html | > Entering new ConversationChain chain...
Prompt after formatting:
The following is a friendly conversation between a human and an AI. The AI is talkative and provides lots of specific details from its context. If the AI does not know the answer to a question, it truthfully says it does not know.
Current conversation:
... |
b6daf3c8b0cc-0 | https://python.langchain.com/en/latest/modules/memory/examples/dynamodb_chat_message_history.html | .ipynb
.pdf
Dynamodb Chat Message History
Contents
DynamoDBChatMessageHistory
Agent with DynamoDB Memory
Dynamodb Chat Message History#
This notebook goes over how to use Dynamodb to store chat message history.
First make sure you have correctly configured the AWS CLI. Then make sure you have installed boto3.
Next, c... |
b6daf3c8b0cc-1 | https://python.langchain.com/en/latest/modules/memory/examples/dynamodb_chat_message_history.html | from langchain.utilities import PythonREPL
from getpass import getpass
message_history = DynamoDBChatMessageHistory(table_name="SessionTable", session_id="1")
memory = ConversationBufferMemory(memory_key="chat_history", chat_memory=message_history, return_messages=True)
python_repl = PythonREPL()
# You can create the t... |
b6daf3c8b0cc-2 | https://python.langchain.com/en/latest/modules/memory/examples/dynamodb_chat_message_history.html | "action_input": "X Corp. (2023–present)Twitter, Inc. (2006–2023)"
}
> Finished chain.
'X Corp. (2023–present)Twitter, Inc. (2006–2023)'
agent_chain.run(input="My name is Bob.")
> Entering new AgentExecutor chain...
{
"action": "Final Answer",
"action_input": "Hello Bob! How can I assist you today?"
}
> Finished... |
f2a318f6f5ce-0 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | .ipynb
.pdf
Callbacks
Contents
Callbacks
How to use callbacks
When do you want to use each of these?
Using an existing handler
Creating a custom handler
Async Callbacks
Using multiple handlers, passing in handlers
Tracing and Token Counting
Tracing
Token Counting
Callbacks#
LangChain provides a callbacks system that ... |
f2a318f6f5ce-1 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | CallbackHandlers are objects that implement the CallbackHandler interface, which has a method for each event that can be subscribed to. The CallbackManager will call the appropriate method on each handler when the event is triggered.
class BaseCallbackHandler:
"""Base callback handler that can be used to handle cal... |
f2a318f6f5ce-2 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | """Run when tool ends running."""
def on_tool_error(
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
) -> Any:
"""Run when tool errors."""
def on_text(self, text: str, **kwargs: Any) -> Any:
"""Run on arbitrary text."""
def on_agent_action(self, action: AgentActio... |
f2a318f6f5ce-3 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | Constructor callbacks are most useful for use cases such as logging, monitoring, etc., which are not specific to a single request, but rather to the entire chain. For example, if you want to log all the requests made to an LLMChain, you would pass a handler to the constructor.
Request callbacks are most useful for use ... |
f2a318f6f5ce-4 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | chain = LLMChain(llm=llm, prompt=prompt)
chain.run(number=2, callbacks=[handler])
> Entering new LLMChain chain...
Prompt after formatting:
1 + 2 =
> Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
1 + 2 =
> Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
1 + 2 =
>... |
f2a318f6f5ce-5 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | My custom handler, token: dressing
My custom handler, token: !
My custom handler, token:
AIMessage(content='Why did the tomato turn red? Because it saw the salad dressing!', additional_kwargs={})
Async Callbacks#
If you are planning to use the async API, it is recommended to use AsyncCallbackHandler to avoid blocking... |
f2a318f6f5ce-6 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | # To enable streaming, we pass in `streaming=True` to the ChatModel constructor
# Additionally, we pass in a list with our custom handler
chat = ChatOpenAI(max_tokens=25, streaming=True, callbacks=[MyCustomSyncHandler(), MyCustomAsyncHandler()])
await chat.agenerate([[HumanMessage(content="Tell me a joke")]])
zzzz....
... |
f2a318f6f5ce-7 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | LLMResult(generations=[[ChatGeneration(text="Why don't scientists trust atoms?\n\nBecause they make up everything!", generation_info=None, message=AIMessage(content="Why don't scientists trust atoms?\n\nBecause they make up everything!", additional_kwargs={}))]], llm_output={'token_usage': {}, 'model_name': 'gpt-3.5-tu... |
f2a318f6f5ce-8 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | print(f"on_new_token {token}")
def on_llm_error(
self, error: Union[Exception, KeyboardInterrupt], **kwargs: Any
) -> Any:
"""Run when LLM errors."""
def on_chain_start(
self, serialized: Dict[str, Any], inputs: Dict[str, Any], **kwargs: Any
) -> Any:
print(f"on_chain_sta... |
f2a318f6f5ce-9 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | agent.run("What is 2 raised to the 0.235 power?", callbacks=[handler1])
on_chain_start AgentExecutor
on_chain_start LLMChain
on_llm_start OpenAI
on_llm_start (I'm the second handler!!) OpenAI
on_new_token I
on_new_token need
on_new_token to
on_new_token use
on_new_token a
on_new_token calculator
on_new_token to
... |
f2a318f6f5ce-10 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | on_new_token
on_new_token
on_chain_start LLMChain
on_llm_start OpenAI
on_llm_start (I'm the second handler!!) OpenAI
on_new_token I
on_new_token now
on_new_token know
on_new_token the
on_new_token final
on_new_token answer
on_new_token .
on_new_token
Final
on_new_token Answer
on_new_token :
on_new_token 1
on... |
f2a318f6f5ce-11 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | "Who won the US Open men's final in 2019? What is his age raised to the 0.334 power?",
"Who is Olivia Wilde's boyfriend? What is his current age raised to the 0.23 power?",
"Who won the most recent formula 1 grand prix? What is their age raised to the 0.23 power?",
"Who won the US Open women's final in 2019... |
f2a318f6f5ce-12 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | Thought: I now know the final answer
Final Answer: Rafael Nadal, aged 36, won the US Open men's final in 2019 and his age raised to the 0.334 power is 3.3098250249682484.
> Finished chain.
> Entering new AgentExecutor chain...
I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the ... |
f2a318f6f5ce-13 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | agent.run(questions[1]) # this should not be traced
> Entering new AgentExecutor chain...
I need to find out who won the US Open men's final in 2019 and then calculate his age raised to the 0.334 power.
Action: Search
Action Input: "US Open men's final 2019 winner"
Observation: Rafael Nadal defeated Daniil Medvedev i... |
f2a318f6f5ce-14 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | Thought: I need to find out Harry Styles' age.
Action: Search
Action Input: "Harry Styles age"
Observation: 29 years
Thought: I need to calculate 29 raised to the 0.23 power.
Action: Calculator
Action Input: 29^0.23
Observation: Answer: 2.169459462491557
Thought: I now know the final answer.
Final Answer: Harry Styles ... |
f2a318f6f5ce-15 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | Action Input: "US Open men's final 2019 winner"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 ... I need to find out who Olivia Wilde's boyfriend is and then calculate his age raised to the 0.23 power.
Action: S... |
f2a318f6f5ce-16 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | Action Input: 38^0.23Answer: 2.3086081644669734
> Finished chain.
"Rafael Nadal, aged 36, won the US Open men's final in 2019 and his age raised to the 0.334 power is 3.3098250249682484."
Token Counting#
LangChain offers a context manager that allows you to count tokens.
from langchain.callbacks import get_openai_callb... |
f2a318f6f5ce-17 | https://python.langchain.com/en/latest/modules/callbacks/getting_started.html | Tracing and Token Counting
Tracing
Token Counting
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
5abeb16f0ce0-0 | https://python.langchain.com/en/latest/modules/agents/agent_executors.html | .rst
.pdf
Agent Executors
Agent Executors#
Note
Conceptual Guide
Agent executors take an agent and tools and use the agent to decide which tools to call and in what order.
In this part of the documentation we cover other related functionality to agent executors
How to combine agents and vectorstores
How to use the asyn... |
78096fb1870a-0 | https://python.langchain.com/en/latest/modules/agents/getting_started.html | .ipynb
.pdf
Getting Started
Getting Started#
Agents use an LLM to determine which actions to take and in what order.
An action can either be using a tool and observing its output, or returning to the user.
When used correctly agents can be extremely powerful. The purpose of this notebook is to show you how to easily us... |
78096fb1870a-1 | https://python.langchain.com/en/latest/modules/agents/getting_started.html | agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
Now let’s test it out!
agent.run("Who is Leo DiCaprio's girlfriend? What is her current age raised to the 0.43 power?")
> Entering new AgentExecutor chain...
I need to find out who Leo DiCaprio's girlfriend is and then calc... |
4ff1a02ab6a8-0 | https://python.langchain.com/en/latest/modules/agents/agents.html | .rst
.pdf
Agents
Agents#
Note
Conceptual Guide
In this part of the documentation we cover the different types of agents, disregarding which specific tools they are used with.
For a high level overview of the different types of agents, see the below documentation.
Agent Types
For documentation on how to create a custom ... |
a5681d0eb0a1-0 | https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html | .ipynb
.pdf
Plan and Execute
Contents
Plan and Execute
Imports
Tools
Planner, Executor, and Agent
Run Example
Plan and Execute#
Plan and execute agents accomplish an objective by first planning what to do, then executing the sub tasks. This idea is largely inspired by BabyAGI and then the “Plan-and-Solve” paper.
The ... |
a5681d0eb0a1-1 | https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html | > Entering new PlanAndExecute chain...
steps=[Step(value="Search for Leo DiCaprio's girlfriend on the internet."), Step(value='Find her current age.'), Step(value='Raise her current age to the 0.43 power using a calculator or programming language.'), Step(value='Output the result.'), Step(value="Given the above steps t... |
a5681d0eb0a1-2 | https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html | Current objective: value='Find her current age.'
Action:
```
{
"action": "Search",
"action_input": "What is Gigi Hadid's current age?"
}
```
Observation: 28 years
Thought:Previous steps: steps=[(Step(value="Search for Leo DiCaprio's girlfriend on the internet."), StepResponse(response='Leo DiCaprio is currently lin... |
a5681d0eb0a1-3 | https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html | Response: Gigi Hadid's current age raised to the 0.43 power is approximately 4.19.
> Entering new AgentExecutor chain...
Action:
```
{
"action": "Final Answer",
"action_input": "The result is approximately 4.19."
}
```
> Finished chain.
*****
Step: Output the result.
Response: The result is approximately 4.19.
> En... |
8a4333b90516-0 | https://python.langchain.com/en/latest/modules/agents/toolkits.html | .rst
.pdf
Toolkits
Toolkits#
Note
Conceptual Guide
This section of documentation covers agents with toolkits - eg an agent applied to a particular use case.
See below for a full list of agent toolkits
Azure Cognitive Services Toolkit
CSV Agent
Gmail Toolkit
Jira
JSON Agent
OpenAPI agents
Natural Language APIs
Pandas Da... |
c3fabc64a7b7-0 | https://python.langchain.com/en/latest/modules/agents/tools.html | .rst
.pdf
Tools
Tools#
Note
Conceptual Guide
Tools are ways that an agent can use to interact with the outside world.
For an overview of what a tool is, how to use them, and a full list of examples, please see the getting started documentation
Getting Started
Next, we have some examples of customizing and generically w... |
33b5d56fd0b9-0 | https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html | .ipynb
.pdf
Tool Input Schema
Tool Input Schema#
By default, tools infer the argument schema by inspecting the function signature. For more strict requirements, custom input schema can be specified, along with custom validation logic.
from typing import Any, Dict
from langchain.agents import AgentType, initialize_agent... |
33b5d56fd0b9-1 | https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html | The main title of langchain.com is "LANG CHAIN 🦜️🔗 Official Home Page"
agent.run("What's the main title on google.com?")
---------------------------------------------------------------------------
ValidationError Traceback (most recent call last)
Cell In[7], line 1
----> 1 agent.run("What's ... |
33b5d56fd0b9-2 | https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html | 115 self.callback_manager.on_chain_error(e, verbose=self.verbose)
File ~/code/lc/lckg/langchain/agents/agent.py:792, in AgentExecutor._call(self, inputs)
790 # We now enter the agent loop (until it returns something).
791 while self._should_continue(iterations, time_elapsed):
--> 792 next_step_output = ... |
33b5d56fd0b9-3 | https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html | --> 110 run_input = self._parse_input(tool_input)
111 if not self.verbose and verbose is not None:
112 verbose_ = verbose
File ~/code/lc/lckg/langchain/tools/base.py:71, in BaseTool._parse_input(self, tool_input)
69 if issubclass(input_args, BaseModel):
70 key_ = next(iter(input_ar... |
434031d66743-0 | https://python.langchain.com/en/latest/modules/agents/tools/multi_input_tool.html | .ipynb
.pdf
Multi-Input Tools
Contents
Multi-Input Tools with a string format
Multi-Input Tools#
This notebook shows how to use a tool that requires multiple inputs with an agent. The recommended way to do so is with the StructuredTool class.
import os
os.environ["LANGCHAIN_TRACING"] = "true"
from langchain import Op... |
434031d66743-1 | https://python.langchain.com/en/latest/modules/agents/tools/multi_input_tool.html | An alternative to the structured tool would be to use the regular Tool class and accept a single string. The tool would then have to handle the parsing logic to extract the relavent values from the text, which tightly couples the tool representation to the agent prompt. This is still useful if the underlying language m... |
434031d66743-2 | https://python.langchain.com/en/latest/modules/agents/tools/multi_input_tool.html | Observation: 12
Thought: I now know the final answer
Final Answer: 3 times 4 is 12
> Finished chain.
'3 times 4 is 12'
previous
Defining Custom Tools
next
Tool Input Schema
Contents
Multi-Input Tools with a string format
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04,... |
180beac9d23b-0 | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html | .ipynb
.pdf
Defining Custom Tools
Contents
Completely New Tools - String Input and Output
Tool dataclass
Subclassing the BaseTool class
Using the tool decorator
Custom Structured Tools
StructuredTool dataclass
Subclassing the BaseTool
Using the decorator
Modify existing tools
Defining the priorities among Tools
Using... |
180beac9d23b-1 | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html | The ‘Tool’ dataclass wraps functions that accept a single string input and returns a string output.
# Load the tool configs that are needed.
search = SerpAPIWrapper()
llm_math_chain = LLMMathChain(llm=llm, verbose=True)
tools = [
Tool.from_function(
func=search.run,
name = "Search",
descript... |
180beac9d23b-2 | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html | I need to find out Leo DiCaprio's girlfriend's name and her age
Action: Search
Action Input: "Leo DiCaprio girlfriend"
Observation: After rumours of a romance with Gigi Hadid, the Oscar winner has seemingly moved on. First being linked to the television personality in September 2022, it appears as if his "age bracket" ... |
180beac9d23b-3 | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html | You can also directly subclass BaseTool. This is useful if you want more control over the instance variables or if you want to propagate callbacks to nested chains or other tools.
from typing import Optional, Type
from langchain.callbacks.manager import AsyncCallbackManagerForToolRun, CallbackManagerForToolRun
class Cu... |
180beac9d23b-4 | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html | > Entering new AgentExecutor chain...
I need to use custom_search to find out who Leo DiCaprio's girlfriend is, and then use the Calculator to raise her age to the 0.43 power.
Action: custom_search
Action Input: "Leo DiCaprio girlfriend"
Observation: After rumours of a romance with Gigi Hadid, the Oscar winner has seem... |
180beac9d23b-5 | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html | @tool
def search_api(query: str) -> str:
"""Searches the API for the query."""
return f"Results for query {query}"
search_api
You can also provide arguments like the tool name and whether to return directly.
@tool("search", return_direct=True)
def search_api(query: str) -> str:
"""Searches the API for the q... |
180beac9d23b-6 | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html | To dynamically generate a structured tool from a given function, the fastest way to get started is with StructuredTool.from_function().
import requests
from langchain.tools import StructuredTool
def post_message(url: str, body: dict, parameters: Optional[dict] = None) -> str:
"""Sends a POST request to the given ur... |
180beac9d23b-7 | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html | query: str = Field(description="should be a search query")
engine: str = Field(description="should be a search engine")
gl: str = Field(description="should be a country code")
hl: str = Field(description="should be a language code")
class CustomSearchTool(BaseTool):
name = "custom_search"
descriptio... |
180beac9d23b-8 | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html | Now, we show how to load existing tools and modify them directly. In the example below, we do something really simple and change the Search tool to have the name Google Search.
from langchain.agents import load_tools
tools = load_tools(["serpapi", "llm-math"], llm=llm)
tools[0].name = "Google Search"
agent = initialize... |
180beac9d23b-9 | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html | "The age of Leo DiCaprio's girlfriend raised to the 0.43 power is approximately 3.55."
Defining the priorities among Tools#
When you made a Custom tool, you may want the Agent to use the custom tool more than normal tools.
For example, you made a custom tool, which gets information on music from your database. When a u... |
180beac9d23b-10 | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html | > Entering new AgentExecutor chain...
I should use a music search engine to find the answer
Action: Music Search
Action Input: most famous song of christmas'All I Want For Christmas Is You' by Mariah Carey. I now know the final answer
Final Answer: 'All I Want For Christmas Is You' by Mariah Carey.
> Finished chain.
"... |
180beac9d23b-11 | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html | When ToolException is thrown, the agent will not stop working, but will handle the exception according to the handle_tool_error variable of the tool, and the processing result will be returned to the agent as observation, and printed in red.
You can set handle_tool_error to True, set it a unified string value, or set i... |
180beac9d23b-12 | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html | description="useful for when you need to answer questions about current events",
),
]
agent = initialize_agent(
tools,
ChatOpenAI(temperature=0),
agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION,
verbose=True,
)
agent.run("Who is Leo DiCaprio's girlfriend?")
> Entering new AgentExecutor chain...
I should... |
180beac9d23b-13 | https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html | Custom Structured Tools
StructuredTool dataclass
Subclassing the BaseTool
Using the decorator
Modify existing tools
Defining the priorities among Tools
Using tools to return directly
Handling Tool Errors
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
313c5e0b9c36-0 | https://python.langchain.com/en/latest/modules/agents/tools/getting_started.html | .md
.pdf
Getting Started
Contents
List of Tools
Getting Started#
Tools are functions that agents can use to interact with the world.
These tools can be generic utilities (e.g. search), other chains, or even other agents.
Currently, tools can be loaded with the following snippet:
from langchain.agents import load_tool... |
313c5e0b9c36-1 | https://python.langchain.com/en/latest/modules/agents/tools/getting_started.html | Tool Description: A wolfram alpha search engine. Useful for when you need to answer questions about Math, Science, Technology, Culture, Society and Everyday Life. Input should be a search query.
Notes: Calls the Wolfram Alpha API and then parses results.
Requires LLM: No
Extra Parameters: wolfram_alpha_appid: The Wolfr... |
313c5e0b9c36-2 | https://python.langchain.com/en/latest/modules/agents/tools/getting_started.html | Tool Description: Useful for when you want to get weather information from the OpenMeteo API. The input should be a question in natural language that this API can answer.
Notes: A natural language connection to the Open Meteo API (https://api.open-meteo.com/), specifically the /v1/forecast endpoint.
Requires LLM: Yes
n... |
313c5e0b9c36-3 | https://python.langchain.com/en/latest/modules/agents/tools/getting_started.html | Notes: SearxNG is easy to deploy self-hosted. It is a good privacy friendly alternative to Google Search. Uses the SearxNG API.
Requires LLM: No
Extra Parameters: searx_host
google-serper
Tool Name: Search
Tool Description: A low-cost Google Search API. Useful for when you need to answer questions about current events.... |
313c5e0b9c36-4 | https://python.langchain.com/en/latest/modules/agents/tools/getting_started.html | previous
Tools
next
Defining Custom Tools
Contents
List of Tools
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 04, 2023. |
15b108aac948-0 | https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html | .ipynb
.pdf
Zapier Natural Language Actions API
Contents
Zapier Natural Language Actions API
Example with Agent
Example with SimpleSequentialChain
Zapier Natural Language Actions API#
Full docs here: https://nla.zapier.com/api/v1/docs
Zapier Natural Language Actions gives you access to the 5k+ apps, 20k+ actions on Z... |
15b108aac948-1 | https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html | # get from https://nla.zapier.com/demo/provider/debug (under User Information, after logging in):
os.environ["ZAPIER_NLA_API_KEY"] = os.environ.get("ZAPIER_NLA_API_KEY", "")
Example with Agent#
Zapier tools can be used with an agent. See the example below.
from langchain.llms import OpenAI
from langchain.agents import... |
15b108aac948-2 | https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html | Observation: {"from__name": "Silicon Valley Bridge Bank, N.A.", "from__email": "sreply@svb.com", "body_plain": "Dear Clients, After chaotic, tumultuous & stressful days, we have clarity on path for SVB, FDIC is fully insuring all deposits & have an ask for clients & partners as we rebuild. Tim Mayopoulos <https://eml.s... |
15b108aac948-3 | https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html | Observation: {"message__text": "Silicon Valley Bank has announced that Tim Mayopoulos is the new CEO. FDIC is fully insuring all deposits and they have an ask for clients and partners as they rebuild.", "message__permalink": "https://langchain.slack.com/archives/C04TSGU0RA7/p1678859932375259", "channel": "C04TSGU0RA7",... |
15b108aac948-4 | https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html | from langchain.tools.zapier.tool import ZapierNLARunAction
from langchain.utilities.zapier import ZapierNLAWrapper
## step 0. expose gmail 'find email' and slack 'send direct message' actions
# first go here, log in, expose (enable) the two actions: https://nla.zapier.com/demo/start -- for this example, can leave all f... |
15b108aac948-5 | https://python.langchain.com/en/latest/modules/agents/tools/examples/zapier.html | action = next((a for a in actions if a["description"].startswith("Slack: Send Direct Message")), None)
instructions = f'Send this to {SLACK_HANDLE} in Slack: {inputs["draft_reply"]}'
return {"slack_data": ZapierNLARunAction(action_id=action["id"], zapier_description=action["description"], params_schema=action["... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.