id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
ddaf65259e45-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 |
9ff5d0e99cd2-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 |
9ff5d0e99cd2-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 |
434cd946fe31-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 |
434cd946fe31-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 |
434cd946fe31-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 |
434cd946fe31-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 |
434cd946fe31-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 |
434cd946fe31-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 |
434cd946fe31-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 |
eb19ddb7bf97-0 | .ipynb
.pdf
How to use the async API for Agents
Contents
Serial vs. Concurrent Execution
How to use the async API for Agents#
LangChain provides async support for Agents by leveraging the asyncio library.
Async methods are currently supported for the following Tools: GoogleSerperAPIWrapper, SerpAPIWrapper and LLMMath... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
eb19ddb7bf97-1 | ]
llm = OpenAI(temperature=0)
tools = load_tools(["google-serper", "llm-math"], llm=llm)
agent = initialize_agent(
tools, llm, agent=AgentType.ZERO_SHOT_REACT_DESCRIPTION, verbose=True
)
s = time.perf_counter()
for q in questions:
agent.run(q)
elapsed = time.perf_counter() - s
print(f"Serial executed in {elapse... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
eb19ddb7bf97-2 | Observation: Rafael Nadal defeated Daniil Medvedev in the final, 7–5, 6–3, 5–7, 4–6, 6–4 to win the men's singles tennis title at the 2019 US Open. It was his fourth US ... Draw: 128 (16 Q / 8 WC). Champion: Rafael Nadal. Runner-up: Daniil Medvedev. Score: 7–5, 6–3, 5–7, 4–6, 6–4. Bianca Andreescu won the women's singl... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
eb19ddb7bf97-3 | 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 |
eb19ddb7bf97-4 | Thought: 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
Observation: Answer: 3.215019829667466
Thought: I now know the final answer.
Final Answer: Rafael Nadal won the US Open men's final in 2019 and his age raised to the 0.334 power is... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
eb19ddb7bf97-5 | Action: Google Serper
Action Input: "who won the most recent formula 1 grand prix"
Observation: Max Verstappen won his first Formula 1 world title on Sunday after the championship was decided by a last-lap overtake of his rival Lewis Hamilton in the Abu Dhabi Grand Prix. Dec 12, 2021
Thought: I need to find out Max Ver... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
eb19ddb7bf97-6 | Observation: Answer: 2.7212987634680084
Thought: I now know the final answer.
Final Answer: Nineteen-year-old Canadian Bianca Andreescu won the US Open women's final in 2019 and her age raised to the 0.34 power is 2.7212987634680084.
> Finished chain.
> Entering new AgentExecutor chain...
I need to find out who Beyonc... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
eb19ddb7bf97-7 | await asyncio.gather(*tasks)
elapsed = time.perf_counter() - s
print(f"Concurrent executed in {elapsed:0.2f} seconds.")
> Entering new AgentExecutor chain...
> Entering new AgentExecutor chain...
> Entering new AgentExecutor chain...
> Entering new AgentExecutor chain...
> Entering new AgentExecutor chain...
I need to... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
eb19ddb7bf97-8 | Thought:
Observation: Jay-Z
Thought: | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
eb19ddb7bf97-9 | Observation: Rafael Nadal defeated Daniil Medvedev in the final, 7–5, 6–3, 5–7, 4–6, 6–4 to win the men's singles tennis title at the 2019 US Open. It was his fourth US ... Draw: 128 (16 Q / 8 WC). Champion: Rafael Nadal. Runner-up: Daniil Medvedev. Score: 7–5, 6–3, 5–7, 4–6, 6–4. Bianca Andreescu won the women's singl... | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
eb19ddb7bf97-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 |
eb19ddb7bf97-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 |
eb19ddb7bf97-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 |
eb19ddb7bf97-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 |
eb19ddb7bf97-14 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/async_agent.html |
426c92e6451b-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 |
426c92e6451b-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 |
426c92e6451b-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 |
426c92e6451b-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 |
426c92e6451b-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 |
426c92e6451b-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 |
426c92e6451b-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 |
426c92e6451b-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 25, 2023. | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/agent_vectorstore.html |
44636a36390a-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 |
44636a36390a-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 |
44636a36390a-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 25, 2023. | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/intermediate_steps.html |
51d21d57673c-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 |
51d21d57673c-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 |
51d21d57673c-2 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/modules/agents/agent_executors/examples/max_iterations.html |
f9f101d3484f-0 | .rst
.pdf
Text Embedding Models
Text Embedding Models#
Note
Conceptual Guide
This documentation goes over how to use the Embedding class in LangChain.
The Embedding class is a class designed for interfacing with embeddings. There are lots of Embedding providers (OpenAI, Cohere, Hugging Face, etc) - this class is design... | https://python.langchain.com/en/latest/modules/models/text_embedding.html |
cc73eb5dfc07-0 | .ipynb
.pdf
Getting Started
Contents
Language Models
text -> text interface
messages -> message interface
Getting Started#
One of the core value props of LangChain is that it provides a standard interface to models. This allows you to swap easily between models. At a high level, there are two main types of models:
La... | https://python.langchain.com/en/latest/modules/models/getting_started.html |
cc73eb5dfc07-1 | Contents
Language Models
text -> text interface
messages -> message interface
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/modules/models/getting_started.html |
56c24aa75f8e-0 | .rst
.pdf
LLMs
LLMs#
Note
Conceptual Guide
Large Language Models (LLMs) are a core component of LangChain.
LangChain is not a provider of LLMs, but rather provides a standard interface through which
you can interact with a variety of LLMs.
The following sections of documentation are provided:
Getting Started: An overvi... | https://python.langchain.com/en/latest/modules/models/llms.html |
67ab1083a4c5-0 | .rst
.pdf
Chat Models
Chat Models#
Note
Conceptual Guide
Chat models are a variation on language models.
While chat models use language models under the hood, the interface they expose is a bit different.
Rather than expose a “text in, text out” API, they expose an interface where “chat messages” are the inputs and out... | https://python.langchain.com/en/latest/modules/models/chat.html |
ee00853d17d3-0 | .ipynb
.pdf
MosaicML embeddings
MosaicML embeddings#
MosaicML offers a managed inference service. You can either use a variety of open source models, or deploy your own.
This example goes over how to use LangChain to interact with MosaicML Inference for text embedding.
# sign up for an account: https://forms.mosaicml.c... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/mosaicml.html |
d1fe9cd2a2ae-0 | .ipynb
.pdf
Sentence Transformers Embeddings
Sentence Transformers Embeddings#
SentenceTransformers embeddings are called using the HuggingFaceEmbeddings integration. We have also added an alias for SentenceTransformerEmbeddings for users who are more familiar with directly using that package.
SentenceTransformers is a... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/sentence_transformers.html |
6792efdf762c-0 | .ipynb
.pdf
TensorflowHub
TensorflowHub#
Let’s load the TensorflowHub Embedding class.
from langchain.embeddings import TensorflowHubEmbeddings
embeddings = TensorflowHubEmbeddings()
2023-01-30 23:53:01.652176: I tensorflow/core/platform/cpu_feature_guard.cc:193] This TensorFlow binary is optimized with oneAPI Deep Neu... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/tensorflowhub.html |
806e4b2f2953-0 | .ipynb
.pdf
SageMaker Endpoint Embeddings
SageMaker Endpoint Embeddings#
Let’s load the SageMaker Endpoints Embeddings class. The class can be used if you host, e.g. your own Hugging Face model on SageMaker.
For instructions on how to do this, please see here. Note: In order to handle batched requests, you will need to... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/sagemaker-endpoint.html |
806e4b2f2953-1 | query_result = embeddings.embed_query("foo")
doc_results = embeddings.embed_documents(["foo"])
doc_results
previous
OpenAI
next
Self Hosted Embeddings
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/sagemaker-endpoint.html |
7137f71f6ec2-0 | .ipynb
.pdf
InstructEmbeddings
InstructEmbeddings#
Let’s load the HuggingFace instruct Embeddings class.
from langchain.embeddings import HuggingFaceInstructEmbeddings
embeddings = HuggingFaceInstructEmbeddings(
query_instruction="Represent the query for retrieval: "
)
load INSTRUCTOR_Transformer
max_seq_length 51... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/instruct_embeddings.html |
0c806b4da3c8-0 | .ipynb
.pdf
Cohere
Cohere#
Let’s load the Cohere Embedding class.
from langchain.embeddings import CohereEmbeddings
embeddings = CohereEmbeddings(cohere_api_key=cohere_api_key)
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
previous
AzureOpe... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/cohere.html |
a178d3eb670f-0 | .ipynb
.pdf
Aleph Alpha
Contents
Asymmetric
Symmetric
Aleph Alpha#
There are two possible ways to use Aleph Alpha’s semantic embeddings. If you have texts with a dissimilar structure (e.g. a Document and a Query) you would want to use asymmetric embeddings. Conversely, for texts with comparable structures, symmetric ... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/aleph_alpha.html |
2d75c555a7b5-0 | .ipynb
.pdf
AzureOpenAI
AzureOpenAI#
Let’s load the OpenAI Embedding class with environment variables set to indicate to use Azure endpoints.
# set the environment variables needed for openai package to know to reach out to azure
import os
os.environ["OPENAI_API_TYPE"] = "azure"
os.environ["OPENAI_API_BASE"] = "https:/... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/azureopenai.html |
a427c6f5f7a5-0 | .ipynb
.pdf
Fake Embeddings
Fake Embeddings#
LangChain also provides a fake embedding class. You can use this to test your pipelines.
from langchain.embeddings import FakeEmbeddings
embeddings = FakeEmbeddings(size=1352)
query_result = embeddings.embed_query("foo")
doc_results = embeddings.embed_documents(["foo"])
prev... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/fake.html |
14d75f8a5c6f-0 | .ipynb
.pdf
Llama-cpp
Llama-cpp#
This notebook goes over how to use Llama-cpp embeddings within LangChain
!pip install llama-cpp-python
from langchain.embeddings import LlamaCppEmbeddings
llama = LlamaCppEmbeddings(model_path="/path/to/model/ggml-model-q4_0.bin")
text = "This is a test document."
query_result = llama.e... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/llamacpp.html |
653d23b039cf-0 | .ipynb
.pdf
Self Hosted Embeddings
Self Hosted Embeddings#
Let’s load the SelfHostedEmbeddings, SelfHostedHuggingFaceEmbeddings, and SelfHostedHuggingFaceInstructEmbeddings classes.
from langchain.embeddings import (
SelfHostedEmbeddings,
SelfHostedHuggingFaceEmbeddings,
SelfHostedHuggingFaceInstructEmbeddi... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/self-hosted.html |
653d23b039cf-1 | tokenizer = AutoTokenizer.from_pretrained(model_id)
model = AutoModelForCausalLM.from_pretrained(model_id)
return pipeline("feature-extraction", model=model, tokenizer=tokenizer)
def inference_fn(pipeline, prompt):
# Return last hidden state of the model
if isinstance(prompt, list):
return [emb[... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/self-hosted.html |
ad5ccfcf3324-0 | .ipynb
.pdf
Hugging Face Hub
Hugging Face Hub#
Let’s load the Hugging Face Embedding class.
from langchain.embeddings import HuggingFaceEmbeddings
embeddings = HuggingFaceEmbeddings()
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
previous
G... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/huggingfacehub.html |
5fe5e2c62d2d-0 | .ipynb
.pdf
Jina
Jina#
Let’s load the Jina Embedding class.
from langchain.embeddings import JinaEmbeddings
embeddings = JinaEmbeddings(jina_auth_token=jina_auth_token, model_name="ViT-B-32::openai")
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([t... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/jina.html |
4a96bde1a38e-0 | .ipynb
.pdf
OpenAI
OpenAI#
Let’s load the OpenAI Embedding class.
from langchain.embeddings import OpenAIEmbeddings
embeddings = OpenAIEmbeddings()
text = "This is a test document."
query_result = embeddings.embed_query(text)
doc_result = embeddings.embed_documents([text])
Let’s load the OpenAI Embedding class with fir... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/openai.html |
c9f2b3df08af-0 | .ipynb
.pdf
Contents
!pip -q install elasticsearch langchain
import elasticsearch
from langchain.embeddings.elasticsearch import ElasticsearchEmbeddings
# Define the model ID
model_id = 'your_model_id'
# Instantiate ElasticsearchEmbeddings using credentials
embeddings = ElasticsearchEmbeddings.from_credentials(
m... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/elasticsearch.html |
b755c12b36c1-0 | .ipynb
.pdf
ModelScope
ModelScope#
Let’s load the ModelScope Embedding class.
from langchain.embeddings import ModelScopeEmbeddings
model_id = "damo/nlp_corom_sentence-embedding_english-base"
embeddings = ModelScopeEmbeddings(model_id=model_id)
text = "This is a test document."
query_result = embeddings.embed_query(tex... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/modelscope_hub.html |
822449194bed-0 | .ipynb
.pdf
Google Cloud Platform Vertex AI PaLM
Google Cloud Platform Vertex AI PaLM#
Note: This is seperate from the Google PaLM integration. Google has chosen to offer an enterprise version of PaLM through GCP, and this supports the models made available through there.
PaLM API on Vertex AI is a Preview offering, su... | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/google_vertex_ai_palm.html |
822449194bed-1 | previous
Fake Embeddings
next
Hugging Face Hub
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/modules/models/text_embedding/examples/google_vertex_ai_palm.html |
63cc519cabdf-0 | .rst
.pdf
How-To Guides
How-To Guides#
The examples here all address certain “how-to” guides for working with chat models.
How to use few shot examples
How to stream responses
previous
Getting Started
next
How to use few shot examples
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated ... | https://python.langchain.com/en/latest/modules/models/chat/how_to_guides.html |
1b63555da89c-0 | .ipynb
.pdf
Getting Started
Contents
PromptTemplates
LLMChain
Streaming
Getting Started#
This notebook covers how to get started with chat models. The interface is based around messages rather than raw text.
from langchain.chat_models import ChatOpenAI
from langchain import PromptTemplate, LLMChain
from langchain.pro... | https://python.langchain.com/en/latest/modules/models/chat/getting_started.html |
1b63555da89c-1 | [
SystemMessage(content="You are a helpful assistant that translates English to French."),
HumanMessage(content="I love programming.")
],
[
SystemMessage(content="You are a helpful assistant that translates English to French."),
HumanMessage(content="I love artificial intelligenc... | https://python.langchain.com/en/latest/modules/models/chat/getting_started.html |
1b63555da89c-2 | human_template="{text}"
human_message_prompt = HumanMessagePromptTemplate.from_template(human_template)
chat_prompt = ChatPromptTemplate.from_messages([system_message_prompt, human_message_prompt])
# get a chat completion from the formatted messages
chat(chat_prompt.format_prompt(input_language="English", output_langua... | https://python.langchain.com/en/latest/modules/models/chat/getting_started.html |
1b63555da89c-3 | Sparkling water, you're my vibe
Verse 2:
No sugar, no calories, just pure bliss
A drink that's hard to resist
It's the perfect way to quench my thirst
A drink that always comes first
Chorus:
Sparkling water, oh so fine
A drink that's always on my mind
With every sip, I feel alive
Sparkling water, you're my vibe
Bridge:... | https://python.langchain.com/en/latest/modules/models/chat/getting_started.html |
4bf1c3fea115-0 | .rst
.pdf
Integrations
Integrations#
The examples here all highlight how to integrate with different chat models.
Anthropic
Azure
Google Cloud Platform Vertex AI PaLM
OpenAI
PromptLayer ChatOpenAI
previous
How to stream responses
next
Anthropic
By Harrison Chase
© Copyright 2023, Harrison Chase.
Las... | https://python.langchain.com/en/latest/modules/models/chat/integrations.html |
d5d1e0322d11-0 | .ipynb
.pdf
PromptLayer ChatOpenAI
Contents
Install PromptLayer
Imports
Set the Environment API Key
Use the PromptLayerOpenAI LLM like normal
Using PromptLayer Track
PromptLayer ChatOpenAI#
This example showcases how to connect to PromptLayer to start recording your ChatOpenAI requests.
Install PromptLayer#
The promp... | https://python.langchain.com/en/latest/modules/models/chat/integrations/promptlayer_chatopenai.html |
d5d1e0322d11-1 | chat = PromptLayerChatOpenAI(return_pl_id=True)
chat_results = chat.generate([[HumanMessage(content="I am a cat and I want")]])
for res in chat_results.generations:
pl_request_id = res[0].generation_info["pl_request_id"]
promptlayer.track.score(request_id=pl_request_id, score=100)
Using this allows you to track... | https://python.langchain.com/en/latest/modules/models/chat/integrations/promptlayer_chatopenai.html |
14c216e5575d-0 | .ipynb
.pdf
Azure
Azure#
This notebook goes over how to connect to an Azure hosted OpenAI endpoint
from langchain.chat_models import AzureChatOpenAI
from langchain.schema import HumanMessage
BASE_URL = "https://${TODO}.openai.azure.com"
API_KEY = "..."
DEPLOYMENT_NAME = "chat"
model = AzureChatOpenAI(
openai_api_ba... | https://python.langchain.com/en/latest/modules/models/chat/integrations/azure_chat_openai.html |
4255de4a4111-0 | .ipynb
.pdf
Anthropic
Contents
ChatAnthropic also supports async and streaming functionality:
Anthropic#
This notebook covers how to get started with Anthropic chat models.
from langchain.chat_models import ChatAnthropic
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
... | https://python.langchain.com/en/latest/modules/models/chat/integrations/anthropic.html |
001c4c9ebb68-0 | .ipynb
.pdf
OpenAI
OpenAI#
This notebook covers how to get started with OpenAI chat models.
from langchain.chat_models import ChatOpenAI
from langchain.prompts.chat import (
ChatPromptTemplate,
SystemMessagePromptTemplate,
AIMessagePromptTemplate,
HumanMessagePromptTemplate,
)
from langchain.schema impo... | https://python.langchain.com/en/latest/modules/models/chat/integrations/openai.html |
001c4c9ebb68-1 | AIMessage(content="J'adore la programmation.", additional_kwargs={})
previous
Google Cloud Platform Vertex AI PaLM
next
PromptLayer ChatOpenAI
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 25, 2023. | https://python.langchain.com/en/latest/modules/models/chat/integrations/openai.html |
165f60a2c4d0-0 | .ipynb
.pdf
Google Cloud Platform Vertex AI PaLM
Google Cloud Platform Vertex AI PaLM#
Note: This is seperate from the Google PaLM integration. Google has chosen to offer an enterprise version of PaLM through GCP, and this supports the models made available through there.
PaLM API on Vertex AI is a Preview offering, su... | https://python.langchain.com/en/latest/modules/models/chat/integrations/google_vertex_ai_palm.html |
165f60a2c4d0-1 | HumanMessage,
SystemMessage
)
chat = ChatVertexAI()
messages = [
SystemMessage(content="You are a helpful assistant that translates English to French."),
HumanMessage(content="Translate this sentence from English to French. I love programming.")
]
chat(messages)
AIMessage(content='Sure, here is the translat... | https://python.langchain.com/en/latest/modules/models/chat/integrations/google_vertex_ai_palm.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.