id
stringlengths
14
16
text
stringlengths
36
2.73k
source
stringlengths
49
117
85fc73b1b01f-1
Current conversation: Human: Hi there! AI: > Finished chain. " Hi there! It's nice to meet you. How can I help you today?" conversation.predict(input="I'm doing well! Just having a conversation with an AI.") > Entering new ConversationChain chain... Prompt after formatting: The following is a friendly conversation betw...
https://python.langchain.com/en/latest/modules/memory/types/buffer.html
85fc73b1b01f-2
Human: Tell me about yourself. AI: > Finished chain. " Sure! I'm an AI created to help people with their everyday tasks. I'm programmed to understand natural language and provide helpful information. I'm also constantly learning and updating my knowledge base so I can provide more accurate and helpful answers." And tha...
https://python.langchain.com/en/latest/modules/memory/types/buffer.html
19c4fa357ff4-0
.ipynb .pdf ConversationSummaryMemory Contents Initializing with messages Using in a chain ConversationSummaryMemory# Now let’s take a look at using a slightly more complex type of memory - ConversationSummaryMemory. This type of memory creates a summary of the conversation over time. This can be useful for condensin...
https://python.langchain.com/en/latest/modules/memory/types/summary.html
19c4fa357ff4-1
history.add_user_message("hi") history.add_ai_message("hi there!") memory = ConversationSummaryMemory.from_messages(llm=OpenAI(temperature=0), chat_memory=history, return_messages=True) memory.buffer '\nThe human greets the AI, to which the AI responds with a friendly greeting.' Using in a chain# Let’s walk through an ...
https://python.langchain.com/en/latest/modules/memory/types/summary.html
19c4fa357ff4-2
Human: Tell me more about it! AI: > Finished chain. " Sure! The customer is having trouble with their computer not connecting to the internet. I'm helping them troubleshoot the issue and figure out what the problem is. So far, we've tried resetting the router and checking the network settings, but the issue still persi...
https://python.langchain.com/en/latest/modules/memory/types/summary.html
dbf1a3957575-0
.ipynb .pdf Momento Momento# This notebook goes over how to use Momento Cache to store chat message history using the MomentoChatMessageHistory class. See the Momento docs for more detail on how to get set up with Momento. Note that, by default we will create a cache if one with the given name doesn’t already exist. Yo...
https://python.langchain.com/en/latest/modules/memory/examples/momento_chat_message_history.html
da3eaf1989ba-0
.ipynb .pdf Zep Memory Contents REACT Agent Chat Message History Example Initialize the Zep Chat Message History Class and initialize the Agent Add some history data Run the agent Inspect the Zep memory Vector search over the Zep memory Zep Memory# REACT Agent Chat Message History Example# This notebook demonstrates ...
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
da3eaf1989ba-1
session_id = str(uuid4()) # This is a unique identifier for the user # Load your OpenAI key from a .env file from dotenv import load_dotenv load_dotenv() True Initialize the Zep Chat Message History Class and initialize the Agent# ddg = DuckDuckGoSearchRun() tools = [ddg] # Set up Zep Chat History zep_chat_history = Z...
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
da3eaf1989ba-2
"The most well-known adaptation of Octavia Butler's work is the FX series" " Kindred, based on her novel of the same name." ), }, {"role": "human", "content": "Who were her contemporaries?"}, { "role": "ai", "content": ( "Octavia Butler's contemporaries includ...
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
da3eaf1989ba-3
), }, ] for msg in test_history: zep_chat_history.append( HumanMessage(content=msg["content"]) if msg["role"] == "human" else AIMessage(content=msg["content"]) ) Run the agent# Doing so will automatically add the input and response to the Zep memory. agent_chain.run( input="WWhat...
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
da3eaf1989ba-4
Ursula K. Le Guin, Samuel R. Delany, and Joanna Russ. {'role': 'human', 'content': 'What awards did she win?', 'uuid': '9fa75c3c-edae-41e3-b9bc-9fcf16b523c9', 'created_at': '2023-05-25T15:09:41.91662Z', 'token_count': 8} {'role': 'ai', 'content': 'Octavia Butler won the Hugo Award, the Nebula Award, and the MacArthur F...
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
da3eaf1989ba-5
{'role': 'human', 'content': "Write a short synopsis of Butler's book, Parable of the Sower. What is it about?", 'uuid': '5678d056-7f05-4e70-b8e5-f85efa56db01', 'created_at': '2023-05-25T15:09:41.938974Z', 'token_count': 23} {'role': 'ai', 'content': 'Parable of the Sower is a science fiction novel by Octavia Butler, p...
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
da3eaf1989ba-6
{'role': 'ai', 'content': 'Parable of the Sower is a prescient novel that speaks to the challenges facing contemporary society, such as climate change, economic inequality, and the rise of authoritarianism. It is a cautionary tale that warns of the dangers of ignoring these issues and the importance of taking action to...
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
da3eaf1989ba-7
{'uuid': '52cfe3e8-b800-4dd8-a7dd-8e9e4764dfc8', 'created_at': '2023-05-25T15:09:41.913856Z', 'role': 'ai', 'content': "Octavia Butler's contemporaries included Ursula K. Le Guin, Samuel R. Delany, and Joanna Russ.", 'token_count': 27} 0.852352466457884 {'uuid': 'd40da612-0867-4a43-92ec-778b86490a39', 'created_at': '20...
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
da3eaf1989ba-8
{'uuid': '862107de-8f6f-43c0-91fa-4441f01b2b3a', 'created_at': '2023-05-25T15:09:41.898149Z', 'role': 'human', 'content': 'Which books of hers were made into movies?', 'token_count': 11} 0.7954322970428519 {'uuid': '97164506-90fe-4c71-9539-69ebcd1d90a2', 'created_at': '2023-05-25T15:09:41.90887Z', 'role': 'human', 'con...
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
da3eaf1989ba-9
previous Redis Chat Message History next Indexes Contents REACT Agent Chat Message History Example Initialize the Zep Chat Message History Class and initialize the Agent Add some history data Run the agent Inspect the Zep memory Vector search over the Zep memory By Harrison Chase © Copyright 2023, Harris...
https://python.langchain.com/en/latest/modules/memory/examples/zep_memory.html
e5cc100057d4-0
.ipynb .pdf How to add Memory to an Agent How to add Memory to an Agent# This notebook goes over adding memory to an Agent. Before going through this notebook, please walkthrough the following notebooks, as this will build on top of both of them: Adding memory to an LLM Chain Custom Agents In order to add a memory to a...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
e5cc100057d4-1
) memory = ConversationBufferMemory(memory_key="chat_history") We can now construct the LLMChain, with the Memory object, and then create the agent. llm_chain = LLMChain(llm=OpenAI(temperature=0), prompt=prompt) agent = ZeroShotAgent(llm_chain=llm_chain, tools=tools, verbose=True) agent_chain = AgentExecutor.from_agent...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
e5cc100057d4-2
Action: Search Action Input: Population of Canada 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...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
e5cc100057d4-3
> Finished AgentExecutor chain. '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 corr...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
e5cc100057d4-4
Action: Search Action Input: National Anthem of Canada 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...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
e5cc100057d4-5
Thought: I now know the final answer. 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 o...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
e5cc100057d4-6
Action: Search Action Input: Population of Canada 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...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
e5cc100057d4-7
> Finished AgentExecutor chain. '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 an...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
e5cc100057d4-8
Action: Search Action Input: national anthem of [country] 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 o...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
e5cc100057d4-9
Thought: I now know the final answer 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...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory.html
ad8c515acdf3-0
.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...
https://python.langchain.com/en/latest/modules/memory/examples/postgres_chat_message_history.html
94682ae5082a-0
.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...
https://python.langchain.com/en/latest/modules/memory/examples/cassandra_chat_message_history.html
0d37ecf6ca83-0
.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 ...
https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html
0d37ecf6ca83-1
"""Define the variables we are providing to the prompt.""" return [self.memory_key] 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[lis...
https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html
0d37ecf6ca83-2
{entities} Conversation: Human: {input} AI:""" prompt = PromptTemplate( input_variables=["entities", "input"], template=template ) 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...
https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html
0d37ecf6ca83-3
Relevant entity information: Harrison likes machine learning Conversation: Human: What do you think Harrison's favorite subject in college was? AI: > Finished ConversationChain chain. ' From what I know about Harrison, I believe his favorite subject in college was machine learning. He has expressed a strong interest in...
https://python.langchain.com/en/latest/modules/memory/examples/custom_memory.html
94b96bb1b101-0
.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...
https://python.langchain.com/en/latest/modules/memory/examples/multiple_memory.html
94b96bb1b101-1
Summary of conversation: 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 prov...
https://python.langchain.com/en/latest/modules/memory/examples/multiple_memory.html
39bf7d3b2771-0
.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...
https://python.langchain.com/en/latest/modules/memory/examples/motorhead_memory.html
39bf7d3b2771-1
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 Bob, nice to meet you! How are you doing today? Human: wh...
https://python.langchain.com/en/latest/modules/memory/examples/motorhead_memory.html
d0c696d7e20f-0
.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...
https://python.langchain.com/en/latest/modules/memory/examples/redis_chat_message_history.html
f8a11dae8630-0
.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...
https://python.langchain.com/en/latest/modules/memory/examples/mongodb_chat_message_history.html
a8b7059dcbb3-0
.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...
https://python.langchain.com/en/latest/modules/memory/examples/adding_memory.html
a8b7059dcbb3-1
Human: Hi there my friend AI: Hi there, how are you doing today? 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....
https://python.langchain.com/en/latest/modules/memory/examples/adding_memory.html
cf793851075f-0
.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 ...
https://python.langchain.com/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html
cf793851075f-1
{context} {chat_history} Human: {human_input} 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...
https://python.langchain.com/en/latest/modules/memory/examples/adding_memory_chain_multiple_inputs.html
495201855317-0
.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...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
495201855317-1
{chat_history} Question: {input} {agent_scratchpad}""" 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(...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
495201855317-2
Action: Search Action Input: Population of Canada 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...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
495201855317-3
> Finished AgentExecutor chain. '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 corr...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
495201855317-4
Action: Search Action Input: National Anthem of Canada 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...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
495201855317-5
Thought: I now know the final answer. 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 o...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
495201855317-6
Action: Search Action Input: Population of Canada 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...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
495201855317-7
> Finished AgentExecutor chain. '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 an...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
495201855317-8
Action: Search Action Input: national anthem of [country] 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 o...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
495201855317-9
Thought: I now know the final answer 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, Harri...
https://python.langchain.com/en/latest/modules/memory/examples/agent_with_memory_in_db.html
64460fee5317-0
.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...
https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html
64460fee5317-1
Current conversation: Human: Hi there! 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 ...
https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html
64460fee5317-2
> 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: ...
https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html
64460fee5317-3
verbose=True, memory=ConversationBufferMemory(human_prefix="Friend") ) conversation.predict(input="Hi there!") > 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 co...
https://python.langchain.com/en/latest/modules/memory/examples/conversational_customization.html
d2336f83f44f-0
.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...
https://python.langchain.com/en/latest/modules/memory/examples/dynamodb_chat_message_history.html
d2336f83f44f-1
from langchain.agents import initialize_agent from langchain.agents import AgentType 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=mes...
https://python.langchain.com/en/latest/modules/memory/examples/dynamodb_chat_message_history.html
d2336f83f44f-2
} Observation: X Corp. (2023–present)Twitter, Inc. (2006–2023) Thought:{ "action": "Final Answer", "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.....
https://python.langchain.com/en/latest/modules/memory/examples/dynamodb_chat_message_history.html
f83b97ad51cd-0
.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 ...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-1
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...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-2
def on_tool_end(self, output: str, **kwargs: Any) -> Any: """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 a...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-3
The verbose argument is available on most objects throughout the API (Chains, Models, Tools, Agents, etc.) as a constructor argument, eg. LLMChain(verbose=True), and it is equivalent to passing a ConsoleCallbackHandler to the callbacks argument of that object and all child objects. This is useful for debugging, as it w...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-4
# First, let's explicitly set the StdOutCallbackHandler in `callbacks` chain = LLMChain(llm=llm, prompt=prompt, callbacks=[handler]) chain.run(number=2) # Then, let's use the `verbose` flag to achieve the same result chain = LLMChain(llm=llm, prompt=prompt, verbose=True) chain.run(number=2) # Finally, let's use the req...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-5
chat([HumanMessage(content="Tell me a joke")]) My custom handler, token: My custom handler, token: Why My custom handler, token: did My custom handler, token: the My custom handler, token: tomato My custom handler, token: turn My custom handler, token: red My custom handler, token: ? My custom handler, token: Be...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-6
self, serialized: Dict[str, Any], prompts: List[str], **kwargs: Any ) -> None: """Run when chain starts running.""" print("zzzz....") await asyncio.sleep(0.3) class_name = serialized["name"] print("Hi! I just woke up. Your llm is starting") async def on_llm_end(self, resp...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-7
Sync handler being called in a `thread_pool_executor`: token: they Sync handler being called in a `thread_pool_executor`: token: make Sync handler being called in a `thread_pool_executor`: token: up Sync handler being called in a `thread_pool_executor`: token: everything Sync handler being called in a `thread_pool_...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-8
from langchain.agents import AgentType, initialize_agent, load_tools from langchain.callbacks import tracing_enabled from langchain.llms import OpenAI # First, define custom callback handler implementations class MyCustomHandlerOne(BaseCallbackHandler): def on_llm_start( self, serialized: Dict[str, Any], pr...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-9
handler1 = MyCustomHandlerOne() handler2 = MyCustomHandlerTwo() # Setup the agent. Only the `llm` will issue callbacks for handler2 llm = OpenAI(temperature=0, streaming=True, callbacks=[handler2]) tools = load_tools(["llm-math"], llm=llm) agent = initialize_agent( tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRI...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-10
on_chain_start LLMChain on_llm_start OpenAI on_llm_start (I'm the second handler!!) OpenAI on_new_token on_new_token ```text on_new_token on_new_token 2 on_new_token ** on_new_token 0 on_new_token . on_new_token 235 on_new_token on_new_token ``` on_new_token ... on_new_token num on_new_token expr on_new_token . on_n...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-11
Using a context manager with tracing_enabled() to trace a particular block of code. Note if the environment variable is set, all code will be traced, regardless of whether or not it’s within the context manager. import os from langchain.agents import AgentType, initialize_agent, load_tools from langchain.callbacks impo...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-12
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: I need to find out the age of the winner Action: Search Action Input: "Rafa...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-13
Action: Calculator Action Input: 29^0.23 Observation: Answer: 2.169459462491557 Thought: I now know the final answer. Final Answer: Harry Styles is Olivia Wilde's boyfriend and his current age raised to the 0.23 power is 2.169459462491557. > Finished chain. # Now, we unset the environment variable and use a context man...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-14
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 ...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-15
task = asyncio.create_task(agent.arun(questions[0])) # this should not be traced with tracing_enabled() as session: assert session tasks = [agent.arun(q) for q in questions[1:3]] # these should be traced await asyncio.gather(*tasks) await task > Entering new AgentExecutor chain... > Entering new AgentExec...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-16
Action: Search Action Input: "Rafael Nadal age"36 years I need to find out Harry Styles' age. Action: Search Action Input: "Harry Styles age" I need to find out Lewis Hamilton's age Action: Search Action Input: "Lewis Hamilton Age"29 years I need to calculate the age raised to the 0.334 power Action: Calculator Action ...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
f83b97ad51cd-17
with get_openai_callback() as cb: await asyncio.gather( *[llm.agenerate(["What is the square root of 4?"]) for _ in range(3)] ) assert cb.total_tokens == total_tokens * 3 # The context manager is concurrency safe task = asyncio.create_task(llm.agenerate(["What is the square root of 4?"])) with get_opena...
https://python.langchain.com/en/latest/modules/callbacks/getting_started.html
8c4999df65d0-0
.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...
https://python.langchain.com/en/latest/modules/agents/agent_executors.html
c65d63464450-0
.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...
https://python.langchain.com/en/latest/modules/agents/getting_started.html
c65d63464450-1
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...
https://python.langchain.com/en/latest/modules/agents/getting_started.html
f746ce34a33a-0
.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 ...
https://python.langchain.com/en/latest/modules/agents/agents.html
7bf9181c1008-0
.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 ...
https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html
7bf9181c1008-1
> 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...
https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html
7bf9181c1008-2
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...
https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html
7bf9181c1008-3
Step: Raise her current age to the 0.43 power using a calculator or programming language. 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." } ``` > Finis...
https://python.langchain.com/en/latest/modules/agents/plan_and_execute.html
e81c19074ad5-0
.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...
https://python.langchain.com/en/latest/modules/agents/toolkits.html
636ffff0d0d1-0
.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...
https://python.langchain.com/en/latest/modules/agents/tools.html
7d38fd850b92-0
.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...
https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html
7d38fd850b92-1
answer = agent.run("What's the main title on langchain.com?") print(answer) The main title of langchain.com is "LANG CHAIN 🦜️🔗 Official Home Page" agent.run("What's the main title on google.com?") --------------------------------------------------------------------------- ValidationError Tra...
https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html
7d38fd850b92-2
112 try: --> 113 outputs = self._call(inputs) 114 except (KeyboardInterrupt, Exception) as e: 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 ...
https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html
7d38fd850b92-3
103 tool_input: Union[str, Dict], (...) 107 **kwargs: Any, 108 ) -> str: 109 """Run the tool.""" --> 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...
https://python.langchain.com/en/latest/modules/agents/tools/tool_input_validation.html
a1f308947045-0
.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...
https://python.langchain.com/en/latest/modules/agents/tools/multi_input_tool.html
a1f308947045-1
'3 times 4 is 12' Multi-Input Tools with a string format# 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...
https://python.langchain.com/en/latest/modules/agents/tools/multi_input_tool.html
a1f308947045-2
> Entering new AgentExecutor chain... I need to multiply two numbers Action: Multiplier Action Input: 3,4 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 st...
https://python.langchain.com/en/latest/modules/agents/tools/multi_input_tool.html
a85d300b2eb9-0
.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...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
a85d300b2eb9-1
Tool dataclass# 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", ...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
a85d300b2eb9-2
> Entering new AgentExecutor chain... 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 202...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
a85d300b2eb9-3
Subclassing the BaseTool class# 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, Ca...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
a85d300b2eb9-4
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 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 DiCapr...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html
a85d300b2eb9-5
> Finished chain. '3.547023357958959' Using the tool decorator# To make it easier to define custom tools, a @tool decorator is provided. This decorator can be used to quickly create a Tool from a simple function. The decorator uses the function name as the tool name by default, but this can be overridden by passing a s...
https://python.langchain.com/en/latest/modules/agents/tools/custom_tools.html