id stringlengths 14 16 | text stringlengths 29 2.73k | source stringlengths 49 117 |
|---|---|---|
b7c52421af6f-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 |
b7c52421af6f-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 |
b7c52421af6f-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 |
b7c52421af6f-4 | Set up the Agent#
We can now combine everything to set up our agent
# 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:"],... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html |
b7c52421af6f-5 | {tools}
Use the following format:
Question: the input question you must answer
Thought: you should always think about what to do
Action: the action to take, should be one of [{tool_names}]
Action Input: the input to the action
Observation: the result of the action
... (this Thought/Action/Action Input/Observation can r... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_agent.html |
b7c52421af6f-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 |
9ebdb55f33b4-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 |
9ebdb55f33b4-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 |
9ebdb55f33b4-2 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 02, 2023. | https://python.langchain.com/en/latest/modules/agents/agents/custom_multi_action_agent.html |
9582d06200c9-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 |
9582d06200c9-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 |
9582d06200c9-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 |
9582d06200c9-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 |
9582d06200c9-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 |
9582d06200c9-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 |
9582d06200c9-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 |
c57a7bc5af8d-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 |
c57a7bc5af8d-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 |
6ed4e61648a9-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 |
6ed4e61648a9-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 |
6ed4e61648a9-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 |
6ed4e61648a9-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 |
6ed4e61648a9-4 | Define the stop sequence#
This is important because it tells the LLM when to stop generation.
This depends heavily on the prompt and model you are using. Generally, you want this to be whatever token you use in the prompt to denote the start of an Observation (otherwise, the LLM may hallucinate an observation for you).... | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html |
6ed4e61648a9-5 | 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 Jun 02, 2023. | https://python.langchain.com/en/latest/modules/agents/agents/custom_llm_chat_agent.html |
a34d869d9c5c-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 |
a34d869d9c5c-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 |
a34d869d9c5c-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 |
a34d869d9c5c-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 |
a34d869d9c5c-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 |
2a5229acbea3-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 |
2a5229acbea3-1 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Jun 02, 2023. | https://python.langchain.com/en/latest/modules/agents/agents/agent_types.html |
0c9b9a8e5613-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 |
0c9b9a8e5613-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 |
0c9b9a8e5613-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 |
0c9b9a8e5613-3 | read Improving Document Retrieval with Contextual Compression Note: This post assumes some familiarity with LangChain and is moderately technical. | https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html |
0c9b9a8e5613-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 |
0c9b9a8e5613-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 |
0c9b9a8e5613-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 |
0c9b9a8e5613-7 | becoming a bigger and bigger issue. People are starting to try to tackle this, with OpenAI releasing OpenAI/evals - focused on evaluating OpenAI models. Mar 14, 2023 3 min read LLMs and SQL Francisco Ingham and Jon Luo are two of the community members leading the change on the SQL integrations. We’re really excited to ... | https://python.langchain.com/en/latest/modules/agents/agents/examples/structured_chat.html |
0c9b9a8e5613-8 | 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 |
0c9b9a8e5613-9 | 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 |
0c9b9a8e5613-10 | "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 |
0c9b9a8e5613-11 | 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 |
1f8bc102e136-0 | .ipynb
.pdf
MRKL
MRKL#
This notebook showcases using an agent to replicate the MRKL chain.
This uses the example Chinook database.
To set it up follow the instructions on https://database.guide/2-sample-databases-sqlite/, placing the .db file in a notebooks folder at the root of this repository.
from langchain import L... | https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html |
1f8bc102e136-1 | > Entering new AgentExecutor chain...
I need to find out who Leo DiCaprio's girlfriend is and then calculate her age raised to the 0.43 power.
Action: Search
Action Input: "Who is Leo DiCaprio's girlfriend?"
Observation: DiCaprio met actor Camila Morrone in December 2017, when she was 20 and he was 43. They were spott... | https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html |
1f8bc102e136-2 | > Entering new AgentExecutor chain...
I need to find out the artist's full name and then search the FooBar database for their albums.
Action: Search
Action Input: "The Storm Before the Calm" artist
Observation: The Storm Before the Calm (stylized in all lowercase) is the tenth (and eighth international) studio album b... | https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html |
1f8bc102e136-3 | Thought: I now know the final answer.
Final Answer: The artist who released the album 'The Storm Before the Calm' is Alanis Morissette and the albums of hers in the FooBar database are Jagged Little Pill.
> Finished chain.
"The artist who released the album 'The Storm Before the Calm' is Alanis Morissette and the album... | https://python.langchain.com/en/latest/modules/agents/agents/examples/mrkl.html |
7394cffd17dc-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 |
e377552146e8-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 |
e377552146e8-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 |
69dad52d002a-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 |
69dad52d002a-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 |
69dad52d002a-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 |
dc95dc1569fd-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 |
dc95dc1569fd-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 |
dc95dc1569fd-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 |
dc95dc1569fd-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 |
0b18e6315d19-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 |
0b18e6315d19-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 |
0b18e6315d19-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 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.