id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
6c81de2bc637-10 | Daniil Medvedev in the men's singles final of the U.S. Open on Sunday. Rafael Nadal survived. The 33-year-old defeated Daniil Medvedev in the final of the 2019 U.S. Open to earn his 19th Grand Slam title Sunday ... NEW YORK -- Rafael Nadal defeated Daniil Medvedev in an epic five-set match, 7-5, 6-3, 5-7, 4-6, 6-4 to w... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
6c81de2bc637-11 | Thought:
Observation: WHAT HAPPENED: #SheTheNorth? She the champion. Nineteen-year-old Canadian Bianca Andreescu sealed her first Grand Slam title on Saturday, downing 23-time major champion Serena Williams in the 2019 US Open women's singles final, 6-3, 7-5. Sep 7, 2019
Thought: | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
6c81de2bc637-12 | Thought:
Observation: Lewis Hamilton holds the record for the most race wins in Formula One history, with 103 wins to date. Michael Schumacher, the previous record holder, ... Michael Schumacher (top left) and Lewis Hamilton (top right) have each won the championship a record seven times during their careers, while Seb... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
6c81de2bc637-13 | Action Input: "Harry Styles age" I need to find out Jay-Z's age
Action: Google Serper
Action Input: "How old is Jay-Z?" I now know that Rafael Nadal won the US Open men's final in 2019 and he is 33 years old.
Action: Calculator
Action Input: 33^0.334 I now need to calculate her age raised to the 0.34 power.
Action: Cal... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
6c81de2bc637-14 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
a100862ec355-0 | .ipynb
.pdf
How to cap the max number of iterations
How to cap the max number of iterations#
This notebook walks through how to cap an agent at taking a certain number of steps. This can be useful to ensure that they do not go haywire and take too many steps.
from langchain.agents import load_tools
from langchain.agent... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/max_iterations.html |
a100862ec355-1 | Final Answer: foo
> Finished chain.
'foo'
Now let’s try it again with the max_iterations=2 keyword argument. It now stops nicely after a certain amount of iterations!
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, max_iterations=2)
agent.run(adversarial_prompt)
> Enterin... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/max_iterations.html |
a100862ec355-2 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/max_iterations.html |
5eb32d1f71de-0 | .ipynb
.pdf
How to combine agents and vectorstores
Contents
Create the Vectorstore
Create the Agent
Use the Agent solely as a router
Multi-Hop vectorstore reasoning
How to combine agents and vectorstores#
This notebook covers how to combine agents and vectorstores. The use case for this is that you’ve ingested your d... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
5eb32d1f71de-1 | texts = text_splitter.split_documents(documents)
embeddings = OpenAIEmbeddings()
docsearch = Chroma.from_documents(texts, embeddings, collection_name="state-of-union")
Running Chroma using direct local API.
Using DuckDB in-memory for database. Data will be transient.
state_of_union = RetrievalQA.from_chain_type(llm=llm... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
5eb32d1f71de-2 | ),
]
# Construct the agent. We will use the default agent type here.
# See documentation for a full list of options.
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True)
agent.run("What did biden say about ketanji brown jackson is the state of the union address?")
> Entering n... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
5eb32d1f71de-3 | Action Input: What are the advantages of using ruff over flake8?
Observation: Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quali... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
5eb32d1f71de-4 | Notice that in the above examples the agent did some extra work after querying the RetrievalQAChain. You can avoid that and just return the result directly.
tools = [
Tool(
name = "State of Union QA System",
func=state_of_union.run,
description="useful for when you need to answer questions a... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
5eb32d1f71de-5 | Action Input: What are the advantages of using ruff over flake8?
Observation: Ruff can be used as a drop-in replacement for Flake8 when used (1) without or with a small number of plugins, (2) alongside Black, and (3) on Python 3 code. It also re-implements some of the most popular Flake8 plugins and related code quali... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
5eb32d1f71de-6 | Tool(
name = "Ruff QA System",
func=ruff.run,
description="useful for when you need to answer questions about ruff (a python linter). Input should be a fully formed question, not referencing any obscure pronouns from the conversation before."
),
]
# Construct the agent. We will use the defau... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
5eb32d1f71de-7 | previous
Agent Executors
next
How to use the async API for Agents
Contents
Create the Vectorstore
Create the Agent
Use the Agent solely as a router
Multi-Hop vectorstore reasoning
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
0e2e54afabf7-0 | .ipynb
.pdf
How to use a timeout for the agent
How to use a timeout for the agent#
This notebook walks through how to cap an agent executor after a certain amount of time. This can be useful for safeguarding against long running agent runs.
from langchain.agents import load_tools
from langchain.agents import initialize... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/max_time_limit.html |
0e2e54afabf7-1 | Final Answer: foo
> Finished chain.
'foo'
Now let’s try it again with the max_execution_time=1 keyword argument. It now stops nicely after 1 second (only one iteration usually)
agent = initialize_agent(tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True, max_execution_time=1)
agent.run(adversarial_pro... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/max_time_limit.html |
94ead3e336ac-0 | .ipynb
.pdf
How to create ChatGPT Clone
How to create ChatGPT Clone#
This chain replicates ChatGPT by combining (1) a specific prompt, and (2) the concept of memory.
Shows off the example as in https://www.engraved.blog/building-a-virtual-machine-inside/
from langchain import OpenAI, ConversationChain, LLMChain, Prompt... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-1 | llm=OpenAI(temperature=0),
prompt=prompt,
verbose=True,
memory=ConversationBufferWindowMemory(k=2),
)
output = chatgpt_chain.predict(human_input="I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal o... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-2 | Human: I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. Do not write explanations. Do not type commands unless I instruct you to do so. When I need to tell ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-3 | Human: I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. Do not write explanations. Do not type commands unless I instruct you to do so. When I need to tell ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-4 | Overall, Assistant is a powerful tool that can help with a wide range of tasks and provide valuable insights and information on a wide range of topics. Whether you need help with a specific question or just want to have a conversation about a particular topic, Assistant is here to assist.
Human: I want you to act as a ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-5 | Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-6 | Prompt after formatting:
Assistant is a large language model trained by OpenAI.
Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-li... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-7 | Assistant:
> Finished LLMChain chain.
```
$ echo -e "x=lambda y:y*5+3;print('Result:' + str(x(6)))" > run.py
$ python3 run.py
Result: 33
```
output = chatgpt_chain.predict(human_input="""echo -e "print(list(filter(lambda x: all(x%d for d in range(2,x)),range(2,3**10)))[:10])" > run.py && python3 run.py""")
print(output... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-8 | AI:
```
$ touch jokes.txt
$ echo "Why did the chicken cross the road? To get to the other side!" >> jokes.txt
$ echo "What did the fish say when it hit the wall? Dam!" >> jokes.txt
$ echo "Why did the scarecrow win the Nobel Prize? Because he was outstanding in his field!" >> jokes.txt
```
Human: echo -e "x=lambda y:y... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-9 | print(output)
> Entering new LLMChain chain...
Prompt after formatting:
Assistant is a large language model trained by OpenAI.
Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a languag... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-10 | AI:
```
$ echo -e "print(list(filter(lambda x: all(x%d for d in range(2,x)),range(2,3**10)))[:10])" > run.py
$ python3 run.py
[2, 3, 5, 7, 11, 13, 17, 19, 23, 29]
```
Human: echo -e "echo 'Hello from Docker" > entrypoint.sh && echo -e "FROM ubuntu:20.04
COPY entrypoint.sh entrypoint.sh
ENTRYPOINT ["/bin/sh","entrypoin... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-11 | Assistant is constantly learning and improving, and its capabilities are constantly evolving. It is able to process and understand large amounts of text, and can use this knowledge to provide accurate and informative responses to a wide range of questions. Additionally, Assistant is able to generate its own text based ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-12 | ENTRYPOINT ["/bin/sh","entrypoint.sh"]">Dockerfile
$ docker build . -t my_docker_image
$ docker run -t my_docker_image
Hello from Docker
```
Human: nvidia-smi
Assistant:
> Finished LLMChain chain.
```
$ nvidia-smi
Sat May 15 21:45:02 2021
+-------------------------------------------------------------------------... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-13 | Prompt after formatting:
Assistant is a large language model trained by OpenAI.
Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-li... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-14 | Hello from Docker
```
Human: nvidia-smi
AI:
```
$ nvidia-smi
Sat May 15 21:45:02 2021
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 460.32.03 Driver Version: 460.32.03 CUDA Version: 11.2 |
|-------------------------------+----------------------+----------... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-15 | --- bbc.com ping statistics ---
3 packets transmitted, 3 packets received, 0.0% packet loss
round-trip min/avg/max/stddev = 14.945/14.945/14.945/0.000 ms
```
output = chatgpt_chain.predict(human_input="""curl -fsSL "https://api.github.com/repos/pytorch/pytorch/releases/latest" | jq -r '.tag_name' | sed 's/[^0-9\.\-]*//... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-16 | Sat May 15 21:45:02 2021
+-----------------------------------------------------------------------------+
| NVIDIA-SMI 460.32.03 Driver Version: 460.32.03 CUDA Version: 11.2 |
|-------------------------------+----------------------+----------------------+
| GPU Name Persistence-M| Bus-Id ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-17 | ```
Human: curl -fsSL "https://api.github.com/repos/pytorch/pytorch/releases/latest" | jq -r '.tag_name' | sed 's/[^0-9\.\-]*//g'
Assistant:
> Finished LLMChain chain.
```
$ curl -fsSL "https://api.github.com/repos/pytorch/pytorch/releases/latest" | jq -r '.tag_name' | sed 's/[^0-9\.\-]*//g'
1.8.1
```
output = chatgpt_... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-18 | Human: ping bbc.com
AI:
```
$ ping bbc.com
PING bbc.com (151.101.65.81): 56 data bytes
64 bytes from 151.101.65.81: icmp_seq=0 ttl=53 time=14.945 ms
64 bytes from 151.101.65.81: icmp_seq=1 ttl=53 time=14.945 ms
64 bytes from 151.101.65.81: icmp_seq=2 ttl=53 time=14.945 ms
--- bbc.com ping statistics ---
3 packets tran... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-19 | Explore our current openings and apply today. We look forward to hearing from you.
```
output = chatgpt_chain.predict(human_input="curl https://chat.openai.com/chat")
print(output)
> Entering new LLMChain chain...
Prompt after formatting:
Assistant is a large language model trained by OpenAI.
Assistant is designed to b... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-20 | ```
Human: lynx https://www.deepmind.com/careers
AI:
```
$ lynx https://www.deepmind.com/careers
DeepMind Careers
Welcome to DeepMind Careers. We are a world-leading artificial intelligence research and development company, and we are looking for talented people to join our team.
We offer a range of exciting opportuni... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-21 | Prompt after formatting:
Assistant is a large language model trained by OpenAI.
Assistant is designed to be able to assist with a wide range of tasks, from answering simple questions to providing in-depth explanations and discussions on a wide range of topics. As a language model, Assistant is able to generate human-li... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-22 | ```
$ curl https://chat.openai.com/chat
<html>
<head>
<title>OpenAI Chat</title>
</head>
<body>
<h1>Welcome to OpenAI Chat!</h1>
<p>
OpenAI Chat is a natural language processing platform that allows you to interact with OpenAI's AI models in a conversational way.
</p>
<p>
To get st... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-23 | }
```
output = chatgpt_chain.predict(human_input="""curl --header "Content-Type:application/json" --request POST --data '{"message": "I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique cod... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-24 | Human: curl https://chat.openai.com/chat
AI:
```
$ curl https://chat.openai.com/chat
<html>
<head>
<title>OpenAI Chat</title>
</head>
<body>
<h1>Welcome to OpenAI Chat!</h1>
<p>
OpenAI Chat is a natural language processing platform that allows you to interact with OpenAI's AI models in a conve... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
94ead3e336ac-25 | }
```
Human: curl --header "Content-Type:application/json" --request POST --data '{"message": "I want you to act as a Linux terminal. I will type commands and you will reply with what the terminal should show. I want you to only reply with the terminal output inside one unique code block, and nothing else. Do not write... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/chatgpt_clone.html |
48dcab1ed1a0-0 | .ipynb
.pdf
How to add SharedMemory to an Agent and its Tools
How to add SharedMemory to an Agent and its Tools#
This notebook goes over adding memory to both of an Agent and its tools. Before going through this notebook, please walk through the following notebooks, as this will build on top of both of them:
Adding mem... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
48dcab1ed1a0-1 | Tool(
name = "Summary",
func=summry_chain.run,
description="useful for when you summarize a conversation. The input to this tool should be a string, representing who will read this summary."
)
]
prefix = """Have a conversation with a human, answering the following questions as best you can. ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
48dcab1ed1a0-2 | Action: Search
Action Input: "ChatGPT"
Observation: Nov 30, 2022 ... We've trained a model called ChatGPT which interacts in a conversational way. The dialogue format makes it possible for ChatGPT to answer ... ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
48dcab1ed1a0-3 | Thought: I now know the final answer.
Final Answer: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI's GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is also capab... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
48dcab1ed1a0-4 | Action Input: Who developed ChatGPT
Observation: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI's GPT-3 family of large ... Feb 15, 2023 ... Who owns Chat GPT? Chat GPT is owned and developed by AI research and deployment company, OpenAI. Th... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
48dcab1ed1a0-5 | Thought: I now know the final answer
Final Answer: ChatGPT was developed by OpenAI.
> Finished chain.
'ChatGPT was developed by OpenAI.'
agent_chain.run(input="Thanks. Summarize the conversation, for my daughter 5 years old.")
> Entering new AgentExecutor chain...
Thought: I need to simplify the conversation for a 5 ye... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
48dcab1ed1a0-6 | print(agent_chain.memory.buffer)
Human: What is ChatGPT?
AI: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI's GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is a... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
48dcab1ed1a0-7 | Tool(
name = "Summary",
func=summry_chain.run,
description="useful for when you summarize a conversation. The input to this tool should be a string, representing who will read this summary."
)
]
prefix = """Have a conversation with a human, answering the following questions as best you can. ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
48dcab1ed1a0-8 | Action: Search
Action Input: "ChatGPT"
Observation: Nov 30, 2022 ... We've trained a model called ChatGPT which interacts in a conversational way. The dialogue format makes it possible for ChatGPT to answer ... ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
48dcab1ed1a0-9 | Thought: I now know the final answer.
Final Answer: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI's GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is also capab... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
48dcab1ed1a0-10 | Action Input: Who developed ChatGPT
Observation: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI's GPT-3 family of large ... Feb 15, 2023 ... Who owns Chat GPT? Chat GPT is owned and developed by AI research and deployment company, OpenAI. Th... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
48dcab1ed1a0-11 | Thought: I now know the final answer
Final Answer: ChatGPT was developed by OpenAI.
> Finished chain.
'ChatGPT was developed by OpenAI.'
agent_chain.run(input="Thanks. Summarize the conversation, for my daughter 5 years old.")
> Entering new AgentExecutor chain...
Thought: I need to simplify the conversation for a 5 ye... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
48dcab1ed1a0-12 | print(agent_chain.memory.buffer)
Human: What is ChatGPT?
AI: ChatGPT is an artificial intelligence chatbot developed by OpenAI and launched in November 2022. It is built on top of OpenAI's GPT-3 family of large language models and is optimized for dialogue by using Reinforcement Learning with Human-in-the-Loop. It is a... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/sharedmemory_for_tools.html |
c184d626d979-0 | .ipynb
.pdf
How to access intermediate steps
How to access intermediate steps#
In order to get more visibility into what an agent is doing, we can also return intermediate steps. This comes in the form of an extra key in the return value, which is a list of (action, observation) tuples.
from langchain.agents import loa... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/intermediate_steps.html |
c184d626d979-1 | > Finished chain.
# The actual return type is a NamedTuple for the agent action, and then an observation
print(response["intermediate_steps"])
[(AgentAction(tool='Search', tool_input='Leo DiCaprio girlfriend', log=' I should look up who Leo DiCaprio is dating\nAction: Search\nAction Input: "Leo DiCaprio girlfriend"'), ... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/intermediate_steps.html |
c184d626d979-2 | ],
"Answer: 3.991298452658078\n"
]
]
previous
Handle Parsing Errors
next
How to cap the max number of iterations
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/intermediate_steps.html |
9d03ada05631-0 | .ipynb
.pdf
Handle Parsing Errors
Contents
Setup
Error
Default error handling
Custom Error Message
Custom Error Function
Handle Parsing Errors#
Occasionally the LLM cannot determine what step to take because it outputs format in incorrect form to be handled by the output parser. In this case, by default the agent err... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/handle_parsing_errors.html |
9d03ada05631-1 | 22 response = json.loads(action.strip())
IndexError: list index out of range
During handling of the above exception, another exception occurred:
OutputParserException Traceback (most recent call last)
Cell In[4], line 1
----> 1 mrkl.run("Who is Leo DiCaprio's girlfriend? No need to add Action")
... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/handle_parsing_errors.html |
9d03ada05631-2 | 135 if new_arg_supported
136 else self._call(inputs)
137 )
138 except (KeyboardInterrupt, Exception) as e:
139 run_manager.on_chain_error(e)
File ~/workplace/langchain/langchain/agents/agent.py:947, in AgentExecutor._call(self, inputs, run_manager)
945 # We now enter the agen... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/handle_parsing_errors.html |
9d03ada05631-3 | 758 Override this to take control of how the agent makes and acts on choices.
759 """
760 try:
761 # Call the LLM to see what to do.
--> 762 output = self.agent.plan(
763 intermediate_steps,
764 callbacks=run_manager.get_child() if run_manager else None,
765 **inp... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/handle_parsing_errors.html |
9d03ada05631-4 | verbose=True,
handle_parsing_errors=True
)
mrkl.run("Who is Leo DiCaprio's girlfriend? No need to add Action")
> Entering new AgentExecutor chain...
Observation: Invalid or incomplete response
Thought:
Observation: Invalid or incomplete response
Thought:Search for Leo DiCaprio's current girlfriend
Action:
```
{
"... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/handle_parsing_errors.html |
9d03ada05631-5 | "action_input": "Who is Leo DiCaprio's girlfriend?"
}
```
Observation: DiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years. He's since been linked to another famous supermodel – Gigi Hadid. The power couple were first supposedly an item in September after being spott... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/handle_parsing_errors.html |
9d03ada05631-6 | "action_input": "Who is Leo DiCaprio's girlfriend?"
}
```
Observation: DiCaprio broke up with girlfriend Camila Morrone, 25, in the summer of 2022, after dating for four years. He's since been linked to another famous supermodel – Gigi Hadid. The power couple were first supposedly an item in September after being spott... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/handle_parsing_errors.html |
402c42b4fe8a-0 | .ipynb
.pdf
Getting Started
Contents
PromptTemplates
to_string
to_messages
Getting Started#
This section contains everything related to prompts. A prompt is the value passed into the Language Model. This value can either be a string (for LLMs) or a list of messages (for Chat Models).
The data types of these prompts a... | https://python.langchain.com/en/latest/modules/prompts/getting_started.html |
402c42b4fe8a-1 | string_prompt_value.to_string()
'tell me a joke about soccer'
chat_prompt_value.to_string()
'Human: tell me a joke about soccer'
to_messages#
This is what is called when passing to ChatModel (which expects a list of messages)
string_prompt_value.to_messages()
[HumanMessage(content='tell me a joke about soccer', additio... | https://python.langchain.com/en/latest/modules/prompts/getting_started.html |
75625c2933c6-0 | .rst
.pdf
Output Parsers
Output Parsers#
Note
Conceptual Guide
Language models output text. But many times you may want to get more structured information than just text back. This is where output parsers come in.
Output parsers are classes that help structure language model responses. There are two main methods an out... | https://python.langchain.com/en/latest/modules/prompts/output_parsers.html |
48ea54bd97e6-0 | .ipynb
.pdf
Chat Prompt Template
Contents
Format output
Different types of MessagePromptTemplate
Chat Prompt Template#
Chat Models takes a list of chat messages as input - this list commonly referred to as a prompt.
These chat messages differ from raw string (which you would pass into a LLM model) in that every messa... | https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html |
48ea54bd97e6-1 | input_variables=["input_language", "output_language"],
)
system_message_prompt_2 = SystemMessagePromptTemplate(prompt=prompt)
assert system_message_prompt == system_message_prompt_2
After that, you can build a ChatPromptTemplate from one or more MessagePromptTemplates. You can use ChatPromptTemplate’s format_prompt – t... | https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html |
48ea54bd97e6-2 | [SystemMessage(content='You are a helpful assistant that translates English to French.', additional_kwargs={}),
HumanMessage(content='I love programming.', additional_kwargs={})]
Different types of MessagePromptTemplate#
LangChain provides different types of MessagePromptTemplate. The most commonly used are AIMessageP... | https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html |
48ea54bd97e6-3 | 3. Practice, practice, practice: The best way to learn programming is through hands-on experience\
""")
chat_prompt.format_prompt(conversation=[human_message, ai_message], word_count="10").to_messages()
[HumanMessage(content='What is the best way to learn programming?', additional_kwargs={}),
AIMessage(content='1. Cho... | https://python.langchain.com/en/latest/modules/prompts/chat_prompt_template.html |
c9c26c9e6cb3-0 | .rst
.pdf
Example Selectors
Example Selectors#
Note
Conceptual Guide
If you have a large number of examples, you may need to select which ones to include in the prompt. The ExampleSelector is the class responsible for doing so.
The base interface is defined as below:
class BaseExampleSelector(ABC):
"""Interface for... | https://python.langchain.com/en/latest/modules/prompts/example_selectors.html |
a674f08e748d-0 | .rst
.pdf
Prompt Templates
Prompt Templates#
Note
Conceptual Guide
Language models take text as input - that text is commonly referred to as a prompt.
Typically this is not simply a hardcoded string but rather a combination of a template, some examples, and user input.
LangChain provides several classes and functions t... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates.html |
fba3b68077f4-0 | .md
.pdf
How to create a custom example selector
Contents
Implement custom example selector
Use custom example selector
How to create a custom example selector#
In this tutorial, we’ll create a custom example selector that selects every alternate example from a given list of examples.
An ExampleSelector must implemen... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/custom_example_selector.html |
fba3b68077f4-1 | # Add new example to the set of examples
example_selector.add_example({"foo": "4"})
example_selector.examples
# -> [{'foo': '1'}, {'foo': '2'}, {'foo': '3'}, {'foo': '4'}]
# Select examples
example_selector.select_examples({"foo": "foo"})
# -> array([{'foo': '1'}, {'foo': '4'}], dtype=object)
previous
Example Selectors... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/custom_example_selector.html |
959b8d11e66a-0 | .ipynb
.pdf
Similarity ExampleSelector
Similarity ExampleSelector#
The SemanticSimilarityExampleSelector selects examples based on which examples are most similar to the inputs. It does this by finding the examples with the embeddings that have the greatest cosine similarity with the inputs.
from langchain.prompts.exam... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/similarity.html |
959b8d11e66a-1 | example_prompt=example_prompt,
prefix="Give the antonym of every input",
suffix="Input: {adjective}\nOutput:",
input_variables=["adjective"],
)
Running Chroma using direct local API.
Using DuckDB in-memory for database. Data will be transient.
# Input is a feeling, so should select the happy/sad example
pr... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/similarity.html |
1ea391359578-0 | .ipynb
.pdf
Maximal Marginal Relevance ExampleSelector
Maximal Marginal Relevance ExampleSelector#
The MaxMarginalRelevanceExampleSelector selects examples based on a combination of which examples are most similar to the inputs, while also optimizing for diversity. It does this by finding the examples with the embeddin... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/mmr.html |
1ea391359578-1 | k=2
)
mmr_prompt = FewShotPromptTemplate(
# We provide an ExampleSelector instead of examples.
example_selector=example_selector,
example_prompt=example_prompt,
prefix="Give the antonym of every input",
suffix="Input: {adjective}\nOutput:",
input_variables=["adjective"],
)
# Input is a feeling,... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/mmr.html |
28271cf7efbe-0 | .ipynb
.pdf
LengthBased ExampleSelector
LengthBased ExampleSelector#
This ExampleSelector selects which examples to use based on length. This is useful when you are worried about constructing a prompt that will go over the length of the context window. For longer inputs, it will select fewer examples to include, while ... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html |
28271cf7efbe-1 | # it is provided as a default value if none is specified.
# get_text_length: Callable[[str], int] = lambda x: len(re.split("\n| ", x))
)
dynamic_prompt = FewShotPromptTemplate(
# We provide an ExampleSelector instead of examples.
example_selector=example_selector,
example_prompt=example_prompt,
pref... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html |
28271cf7efbe-2 | Input: sunny
Output: gloomy
Input: windy
Output: calm
Input: big
Output: small
Input: enthusiastic
Output:
previous
How to create a custom example selector
next
Maximal Marginal Relevance ExampleSelector
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/length_based.html |
d2c1cb83f897-0 | .ipynb
.pdf
NGram Overlap ExampleSelector
NGram Overlap ExampleSelector#
The NGramOverlapExampleSelector selects and orders examples based on which examples are most similar to the input, according to an ngram overlap score. The ngram overlap score is a float between 0.0 and 1.0, inclusive.
The selector allows for a th... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html |
d2c1cb83f897-1 | {"input": "Spot can run.", "output": "Spot puede correr."},
]
example_prompt = PromptTemplate(
input_variables=["input", "output"],
template="Input: {input}\nOutput: {output}",
)
example_selector = NGramOverlapExampleSelector(
# These are the examples it has available to choose from.
examples=examples, ... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html |
d2c1cb83f897-2 | Output: Ver correr a Spot.
Input: My dog barks.
Output: Mi perro ladra.
Input: Spot can run fast.
Output:
# You can add examples to NGramOverlapExampleSelector as well.
new_example = {"input": "Spot plays fetch.", "output": "Spot juega a buscar."}
example_selector.add_example(new_example)
print(dynamic_prompt.format(se... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html |
d2c1cb83f897-3 | Input: Spot plays fetch.
Output: Spot juega a buscar.
Input: Spot can play fetch.
Output:
# Setting threshold greater than 1.0
example_selector.threshold=1.0+1e-9
print(dynamic_prompt.format(sentence="Spot can play fetch."))
Give the Spanish translation of every input
Input: Spot can play fetch.
Output:
previous
Maxima... | https://python.langchain.com/en/latest/modules/prompts/example_selectors/examples/ngram_overlap.html |
16c5a033f09f-0 | .md
.pdf
Getting Started
Contents
What is a prompt template?
Create a prompt template
Template formats
Validate template
Serialize prompt template
Pass few shot examples to a prompt template
Select examples for a prompt template
Getting Started#
In this tutorial, we will learn about:
what a prompt template is, and wh... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
16c5a033f09f-1 | no_input_prompt.format()
# -> "Tell me a joke."
# An example prompt with one input variable
one_input_prompt = PromptTemplate(input_variables=["adjective"], template="Tell me a {adjective} joke.")
one_input_prompt.format(adjective="funny")
# -> "Tell me a funny joke."
# An example prompt with multiple input variables
m... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
16c5a033f09f-2 | # -> Tell me a funny joke about chickens.
Currently, PromptTemplate only supports jinja2 and f-string templating format. If there is any other templating format that you would like to use, feel free to open an issue in the Github page.
Validate template#
By default, PromptTemplate will validate the template string by c... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
16c5a033f09f-3 | To generate a prompt with few shot examples, you can use the FewShotPromptTemplate. This class takes in a PromptTemplate and a list of few shot examples. It then formats the prompt template with the few shot examples.
In this example, we’ll create a prompt to generate word antonyms.
from langchain import PromptTemplate... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
16c5a033f09f-4 | input_variables=["input"],
# The example_separator is the string we will use to join the prefix, examples, and suffix together with.
example_separator="\n",
)
# We can now generate a prompt using the `format` method.
print(few_shot_prompt.format(input="big"))
# -> Give the antonym of every input
# ->
# -> Word... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
16c5a033f09f-5 | {"word": "windy", "antonym": "calm"},
]
# We'll use the `LengthBasedExampleSelector` to select the examples.
example_selector = LengthBasedExampleSelector(
# These are the examples is has available to choose from.
examples=examples,
# This is the PromptTemplate being used to format the examples.
exampl... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
16c5a033f09f-6 | # -> Antonym: lethargic
# ->
# -> Word: sunny
# -> Antonym: gloomy
# ->
# -> Word: windy
# -> Antonym: calm
# ->
# -> Word: big
# -> Antonym:
In contrast, if we provide a very long input, the LengthBasedExampleSelector will select fewer examples to include in the prompt.
long_string = "big and huge and massive and larg... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/getting_started.html |
53d9d50e2a06-0 | .rst
.pdf
How-To Guides
How-To Guides#
If you’re new to the library, you may want to start with the Quickstart.
The user guide here shows more advanced workflows and how to use the library in different ways.
Connecting to a Feature Store
How to create a custom prompt template
How to create a prompt template that uses f... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/how_to_guides.html |
29949ae4550e-0 | .ipynb
.pdf
How to create a prompt template that uses few shot examples
Contents
Use Case
Using an example set
Create the example set
Create a formatter for the few shot examples
Feed examples and formatter to FewShotPromptTemplate
Using an example selector
Feed examples into ExampleSelector
Feed example selector int... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
29949ae4550e-1 | "answer":
"""
Are follow up questions needed here: Yes.
Follow up: Who was the founder of craigslist?
Intermediate answer: Craigslist was founded by Craig Newmark.
Follow up: When was Craig Newmark born?
Intermediate answer: Craig Newmark was born on December 6, 1952.
So the final answer is: December 6, 1952
"""
},
... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
29949ae4550e-2 | print(example_prompt.format(**examples[0]))
Question: Who lived longer, Muhammad Ali or Alan Turing?
Are follow up questions needed here: Yes.
Follow up: How old was Muhammad Ali when he died?
Intermediate answer: Muhammad Ali was 74 years old when he died.
Follow up: How old was Alan Turing when he died?
Intermediate ... | https://python.langchain.com/en/latest/modules/prompts/prompt_templates/examples/few_shot_examples.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.