id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
1b8237072c06-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 |
1b8237072c06-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 |
1b8237072c06-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 |
1b8237072c06-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 |
1b8237072c06-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 |
7c9f736cb4f2-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 |
043943c902e7-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 |
043943c902e7-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 |
043943c902e7-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 |
043943c902e7-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 |
74a4382eed47-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 |
74a4382eed47-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 |
74a4382eed47-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 |
3cd3f029172b-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 |
bb989e7b5476-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 |
bb989e7b5476-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 |
601c65b88872-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 |
402cf7c55968-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 |
402cf7c55968-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 |
402cf7c55968-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 |
402cf7c55968-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 |
75246c7c5f36-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 |
ad3d41ff129a-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 |
ad3d41ff129a-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 |
ad3d41ff129a-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 |
ad3d41ff129a-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 |
ad3d41ff129a-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 |
ad3d41ff129a-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 |
ad3d41ff129a-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 |
ad3d41ff129a-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 |
ad3d41ff129a-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 |
ad3d41ff129a-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 |
1b36a12c4189-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 |
1b36a12c4189-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 |
8dc0fefc17ab-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 |
8dc0fefc17ab-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 |
8dc0fefc17ab-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 |
8dc0fefc17ab-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 |
934e15266797-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 |
8f623bf41455-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 |
8e2907c2b38d-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 |
da3eddb48bd5-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 |
33ad60b6e2a0-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 |
33ad60b6e2a0-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 |
33ad60b6e2a0-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 |
33ad60b6e2a0-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 |
33ad60b6e2a0-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 |
33ad60b6e2a0-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 |
33ad60b6e2a0-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 |
9b1c5abc07a8-0 | .md
.pdf
Agent Types
Contents
zero-shot-react-description
react-docstore
self-ask-with-search
conversational-react-description
Agent Types#
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 a response to the user.
Here a... | https://python.langchain.com/en/latest/modules/agents/agents/agent_types.html |
9b1c5abc07a8-1 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/modules/agents/agents/agent_types.html |
da2c3fc4ba26-0 | .ipynb
.pdf
Custom MultiAction Agent
Custom MultiAction Agent#
This notebook goes through how to create your own custom agent.
An agent consists of two 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 ... | https://python.langchain.com/en/latest/modules/agents/agents/custom_multi_action_agent.html |
da2c3fc4ba26-1 | """
if len(intermediate_steps) == 0:
return [
AgentAction(tool="Search", tool_input=kwargs["input"], log=""),
AgentAction(tool="RandomWord", tool_input=kwargs["input"], log=""),
]
else:
return AgentFinish(return_values={"output": "bar"}... | https://python.langchain.com/en/latest/modules/agents/agents/custom_multi_action_agent.html |
da2c3fc4ba26-2 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/modules/agents/agents/custom_multi_action_agent.html |
fc63046a5a23-0 | .ipynb
.pdf
Custom Agent
Custom Agent#
This notebook goes through how to create your own custom agent.
An agent consists of two 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 langc... | https://python.langchain.com/en/latest/modules/agents/agents/custom_agent.html |
fc63046a5a23-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 |
97672dc63bb1-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 |
97672dc63bb1-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 |
97672dc63bb1-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 |
97672dc63bb1-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 |
97672dc63bb1-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 |
b48560d78944-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 |
b48560d78944-1 | !pip install langchain
!pip install google-search-results
!pip install openai
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 ty... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html |
b48560d78944-2 | 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 the final answer
Final Answer: the final answer to the original input question
These were previous tasks you completed:
Begin!
Question: {input}
{agent_sc... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html |
b48560d78944-3 | # This includes the `intermediate_steps` variable because that is needed
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 pa... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html |
b48560d78944-4 | llm = ChatOpenAI(openai_api_key=OPENAI_API_KEY, temperature=0)
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 Observati... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html |
b48560d78944-5 | 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 the Agent
Use the Agent
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html |
af1d2c11474b-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 |
af1d2c11474b-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 |
af1d2c11474b-2 | Tool(name='foo-95', description='a silly function that you can use to get more information about the number 95', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None),
Tool(name='foo-12', ... | https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html |
af1d2c11474b-3 | Tool(name='foo-14', description='a silly function that you can use to get more information about the number 14', return_direct=False, verbose=False, callback_manager=<langchain.callbacks.shared.SharedCallbackManager object at 0x114b28a90>, func=<function fake_func at 0x15e5bd1f0>, coroutine=None),
Tool(name='foo-11', ... | https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html |
af1d2c11474b-4 | from typing import Callable
# Set up a prompt template
class CustomPromptTemplate(StringPromptTemplate):
# The template to use
template: str
############## NEW ######################
# The list of tools available
tools_getter: Callable
def format(self, **kwargs) -> str:
# Get the in... | https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html |
af1d2c11474b-5 | 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_agent_with_tool_retrieval.html |
af1d2c11474b-6 | output_parser=output_parser,
stop=["\nObservation:"],
allowed_tools=tool_names
)
Use the Agent#
Now we can use it!
agent_executor = AgentExecutor.from_agent_and_tools(agent=agent, tools=tools, verbose=True)
agent_executor.run("What's the weather in SF?")
> Entering new AgentExecutor chain...
Thought: I need to... | https://python.langchain.com/en/latest/modules/agents/agents/custom_agent_with_tool_retrieval.html |
9a92d0878c40-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 |
9a92d0878c40-1 | > Entering new AgentExecutor chain...
{
"action": "Final Answer",
"action_input": "Hello Bob! How can I assist you today?"
}
> Finished chain.
'Hello Bob! How can I assist you today?'
agent_chain.run(input="what's my name?")
> Entering new AgentExecutor chain...
{
"action": "Final Answer",
"action_input... | https://python.langchain.com/en/latest/modules/agents/agents/examples/chat_conversation_agent.html |
9a92d0878c40-2 | > Entering new AgentExecutor chain...
{
"action": "Final Answer",
"action_input": "The last letter in your name is 'b'. Argentina won the World Cup in 1978."
}
> Finished chain.
"The last letter in your name is 'b'. Argentina won the World Cup in 1978."
agent_chain.run(input="whats the weather like in pomfret?"... | https://python.langchain.com/en/latest/modules/agents/agents/examples/chat_conversation_agent.html |
4aa97eab25f3-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 |
3d3c7ed0ee72-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 |
3d3c7ed0ee72-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 |
7c65f6a7fa71-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 |
7c65f6a7fa71-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 |
7c65f6a7fa71-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 |
773d458bad92-0 | .ipynb
.pdf
Structured Tool Chat Agent
Contents
Initialize Tools
Adding in memory
Structured Tool Chat Agent#
This notebook walks through using a chat agent capable of using multi-input tools.
Older agents are configured to specify an action input as a single string, but this agent can use the provided tools’ args_sc... | https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html |
773d458bad92-1 | print(response)
> Entering new AgentExecutor chain...
Action:
```
{
"action": "Final Answer",
"action_input": "Hello Erica, how can I assist you today?"
}
```
> Finished chain.
Hello Erica, how can I assist you today?
response = await agent_chain.arun(input="Don't need help really just chatting.")
print(response)
>... | https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html |
773d458bad92-2 | We recently open-sourced an auto-evaluator tool for grading LLM question-answer chains. We are now releasing an open source, free to use hosted app and API to expand usability. Below we discuss a few opportunities to further improve May 1, 2023 5 min read Callbacks Improvements TL;DR: We're announcing improvements to o... | https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html |
773d458bad92-3 | discussions around a single agent. If multiple Apr 28, 2023 4 min read Gradio & LLM Agents Editor's note: this is a guest blog post from Freddy Boulton, a software engineer at Gradio. We're excited to share this post because it brings a large number of exciting new tools into the ecosystem. Agents are largely defined b... | https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html |
773d458bad92-4 | 💡 TL;DR: We’ve introduced a new abstraction and a new document Retriever to facilitate the post-processing of retrieved documents. Specifically, the new abstraction makes it easy to take a set of retrieved documents and extract from them Apr 20, 2023 3 min read Autonomous Agents & Agent Simulations Over the past two w... | https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html |
773d458bad92-5 | Context
Originally we designed LangChain.js to run in Node.js, which is the Apr 11, 2023 3 min read LangChain x Supabase Supabase is holding an AI Hackathon this week. Here at LangChain we are big fans of both Supabase and hackathons, so we thought this would be a perfect time to highlight the multiple ways you can use... | https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html |
773d458bad92-6 | The reason we like Supabase so much is that Apr 8, 2023 2 min read Announcing our $10M seed round led by Benchmark It was only six months ago that we released the first version of LangChain, but it seems like several years. When we launched, generative AI was starting to go mainstream: stable diffusion had just been re... | https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html |
773d458bad92-7 | This is done with the goals of (1) allowing retrievers constructed elsewhere to be used more easily in LangChain, (2) encouraging more experimentation with alternative Mar 23, 2023 4 min read LangChain + Zapier Natural Language Actions (NLA) We are super excited to team up with Zapier and integrate their new Zapier NLA... | https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html |
773d458bad92-8 | Ingham and Jon Luo are two of the community members leading the change on the SQL integrations. We’re really excited to write this blog post with them going over all the tips and tricks they’ve learned doing so. We’re even more excited to announce that we’ Mar 13, 2023 8 min read Origin Web Browser [Editor's Note]: Thi... | https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html |
773d458bad92-9 | Authors: Parth Asawa (pgasawa@), Ayushi Batwara (ayushi.batwara@), Jason Mar 8, 2023 4 min read Prompt Selectors One common complaint we've heard is that the default prompt templates do not work equally well for all models. This became especially pronounced this past week when OpenAI released a ChatGPT API. This new AP... | https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html |
773d458bad92-10 | What does this mean? It means that all your favorite prompts, chains, and agents are all recreatable in TypeScript natively. Both the Python version and TypeScript version utilize the same serializable format, meaning that artifacts can seamlessly be shared between languages. As an Feb 17, 2023 2 min read Streaming Sup... | https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html |
773d458bad92-11 | "url": "https://xkcd.com/"
}
}
```
Observation: Navigating to https://xkcd.com/ returned status code 200
Thought:I can extract the latest comic title and alt text using CSS selectors.
Action:
```
{
"action": "get_elements",
"action_input": {
"selector": "#ctitle, #comic img",
"attributes": ["alt", "src"]
... | https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html |
773d458bad92-12 | Action:
```
{
"action": "Final Answer",
"action_input": "Hi Erica! How can I assist you today?"
}
```
> Finished chain.
Hi Erica! How can I assist you today?
response = await agent_chain.arun(input="whats my name?")
print(response)
> Entering new AgentExecutor chain...
Your name is Erica.
> Finished chain.
Your nam... | https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html |
6719bfc018a4-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 |
6719bfc018a4-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 |
6719bfc018a4-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 |
6719bfc018a4-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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.