id stringlengths 14 16 | text stringlengths 36 2.73k | source stringlengths 49 117 |
|---|---|---|
66c566c16780-31 | Requirement already satisfied: pydantic>=1.9 in /workspace/langchain/.venv/lib/python3.9/site-packages (from chromadb) (1.10.7)
Requirement already satisfied: hnswlib>=0.7 in /workspace/langchain/.venv/lib/python3.9/site-packages (from chromadb) (0.7.0)
Requirement already satisfied: clickhouse-connect>=0.5.7 in /works... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-32 | Requirement already satisfied: certifi in /workspace/langchain/.venv/lib/python3.9/site-packages (from clickhouse-connect>=0.5.7->chromadb) (2022.12.7)
Requirement already satisfied: urllib3>=1.26 in /workspace/langchain/.venv/lib/python3.9/site-packages (from clickhouse-connect>=0.5.7->chromadb) (1.26.15)
Requirement ... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-33 | Requirement already satisfied: six>=1.5 in /workspace/langchain/.venv/lib/python3.9/site-packages (from posthog>=2.4.0->chromadb) (1.16.0)
Requirement already satisfied: monotonic>=1.5 in /workspace/langchain/.venv/lib/python3.9/site-packages (from posthog>=2.4.0->chromadb) (1.6)
Requirement already satisfied: backoff>... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-34 | Requirement already satisfied: torch>=1.6.0 in /workspace/langchain/.venv/lib/python3.9/site-packages (from sentence-transformers>=2.2.2->chromadb) (1.13.1)
Requirement already satisfied: torchvision in /workspace/langchain/.venv/lib/python3.9/site-packages (from sentence-transformers>=2.2.2->chromadb) (0.14.1)
Require... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-35 | Requirement already satisfied: h11>=0.8 in /workspace/langchain/.venv/lib/python3.9/site-packages (from uvicorn[standard]>=0.18.3->chromadb) (0.14.0)
Requirement already satisfied: httptools>=0.5.0 in /workspace/langchain/.venv/lib/python3.9/site-packages (from uvicorn[standard]>=0.18.3->chromadb) (0.5.0)
Requirement a... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-36 | Requirement already satisfied: packaging>=20.9 in /workspace/langchain/.venv/lib/python3.9/site-packages (from huggingface-hub>=0.4.0->sentence-transformers>=2.2.2->chromadb) (23.1)
Requirement already satisfied: anyio<5,>=3.4.0 in /workspace/langchain/.venv/lib/python3.9/site-packages (from starlette<0.27.0,>=0.26.1->... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-37 | Requirement already satisfied: setuptools in /workspace/langchain/.venv/lib/python3.9/site-packages (from nvidia-cublas-cu11==11.10.3.66->torch>=1.6.0->sentence-transformers>=2.2.2->chromadb) (67.7.1)
Requirement already satisfied: wheel in /workspace/langchain/.venv/lib/python3.9/site-packages (from nvidia-cublas-cu11... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-38 | Requirement already satisfied: pillow!=8.3.*,>=5.3.0 in /workspace/langchain/.venv/lib/python3.9/site-packages (from torchvision->sentence-transformers>=2.2.2->chromadb) (9.5.0)
Requirement already satisfied: sniffio>=1.1 in /workspace/langchain/.venv/lib/python3.9/site-packages (from anyio<5,>=3.4.0->starlette<0.27.0,... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-39 | answer_key = sql_cmd_key # this is the SQL generation input
if step[input_key].endswith("Answer:"):
answer_key = final_answer_key # this is the final answer input
elif sql_cmd_key in step:
_example[sql_cmd_key] = step[sql_cmd_key]
answer_ke... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-40 | warnings.warn(
SELECT firstname FROM customer WHERE firstname LIKE '%a%'
SQLResult: [('François',), ('František',), ('Helena',), ('Astrid',), ('Daan',), ('Kara',), ('Eduardo',), ('Alexandre',), ('Fernanda',), ('Mark',), ('Frank',), ('Jack',), ('Dan',), ('Kathy',), ('Heather',), ('Frank',), ('Richard',), ('Patrick',), (... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-41 | warnings.warn(
[('François', 'Frantiek', 'Helena', 'Astrid', 'Daan', 'Kara', 'Eduardo', 'Alexandre', 'Fernanda', 'Mark', 'Frank', 'Jack', 'Dan', 'Kathy', 'Heather', 'Frank', 'Richard', 'Patrick', 'Julia', 'Edward', 'Martha', 'Aaron', 'Madalena', 'Hannah', 'Niklas', 'Camille', 'Marc', 'Wyatt', 'Isabelle', 'Ladislav', 'L... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-42 | sql_cmd: SELECT firstname FROM customer WHERE firstname LIKE '%a%'
sql_result: '[(''François'',), (''František'',), (''Helena'',), (''Astrid'',), (''Daan'',),
(''Kara'',), (''Eduardo'',), (''Alexandre'',), (''Fernanda'',), (''Mark'',), (''Frank'',),
(''Jack'',), (''Dan'',), (''Kathy'',), (''Heather'',), (''Frank'',... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-43 | \ \n\t\"Phone\" NVARCHAR(24), \n\t\"Fax\" NVARCHAR(24), \n\t\"Email\" NVARCHAR(60)\
\ NOT NULL, \n\t\"SupportRepId\" INTEGER, \n\tPRIMARY KEY (\"CustomerId\"), \n\t\
FOREIGN KEY(\"SupportRepId\") REFERENCES \"Employee\" (\"EmployeeId\")\n)\n\n/*\n\
3 rows from Customer table:\nCustomerId\tFirstName\tLastName\tCom... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-44 | None\tftremblay@gmail.com\t3\n*/"
Run the snippet above a few times, or log exceptions in your deployed environment, to collect lots of examples of inputs, table_info and sql_cmd generated by your language model. The sql_cmd values will be incorrect and you can manually fix them up to build a collection of examples, e.... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-45 | CREATE TABLE "Genre" (
"GenreId" INTEGER NOT NULL,
"Name" NVARCHAR(120),
PRIMARY KEY ("GenreId")
)
/*
3 rows from Genre table:
GenreId Name
1 Rock
2 Jazz
3 Metal
*/
sql_cmd: SELECT "Name" FROM "Genre" WHERE "Name" LIKE 'r%';
sql_result: "[('Rock',), ('Rock and Rol... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-46 | # This is the list of examples available to select from.
examples_dict,
# This is the embedding class used to produce embeddings which are used to measure semantic similarity.
local_embeddings,
# This is the VectorStore clas... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
66c566c16780-47 | Answer:54 customers are not from Brazil.
> Finished chain.
result = local_chain("How many customers are there in total?")
> Entering new SQLDatabaseChain chain...
How many customers are there in total?
SQLQuery:SELECT count(*) FROM Customer;
SQLResult: [(59,)]
Answer:There are 59 customers in total.
> Finished chain.
p... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
eb284835821f-0 | .ipynb
.pdf
PAL
Contents
Math Prompt
Colored Objects
Intermediate Steps
PAL#
Implements Program-Aided Language Models, as in https://arxiv.org/pdf/2211.10435.pdf.
from langchain.chains import PALChain
from langchain import OpenAI
llm = OpenAI(temperature=0, max_tokens=512)
Math Prompt#
pal_chain = PALChain.from_math_... | https://python.langchain.com/en/latest/modules/chains/examples/pal.html |
eb284835821f-1 | objects += [('booklet', 'purple')] * 2
objects += [('sunglasses', 'yellow')] * 2
# Remove all pairs of sunglasses
objects = [object for object in objects if object[0] != 'sunglasses']
# Count number of purple objects
num_purple = len([object for object in objects if object[1] == 'purple'])
answer = num_purple
> Finishe... | https://python.langchain.com/en/latest/modules/chains/examples/pal.html |
eb284835821f-2 | answer = num_purple
> Finished chain.
result['intermediate_steps']
"# Put objects into a list to record ordering\nobjects = []\nobjects += [('booklet', 'blue')] * 2\nobjects += [('booklet', 'purple')] * 2\nobjects += [('sunglasses', 'yellow')] * 2\n\n# Remove all pairs of sunglasses\nobjects = [object for object in obj... | https://python.langchain.com/en/latest/modules/chains/examples/pal.html |
656d6e84d1fc-0 | .ipynb
.pdf
Moderation
Contents
How to use the moderation chain
How to append a Moderation chain to an LLMChain
Moderation#
This notebook walks through examples of how to use a moderation chain, and several common ways for doing so. Moderation chains are useful for detecting text that could be hateful, violent, etc. ... | https://python.langchain.com/en/latest/modules/chains/examples/moderation.html |
656d6e84d1fc-1 | 'This is okay'
moderation_chain.run("I will kill you")
"Text was found that violates OpenAI's content policy."
Here’s an example of using the moderation chain to throw an error.
moderation_chain_error = OpenAIModerationChain(error=True)
moderation_chain_error.run("This is okay")
'This is okay'
moderation_chain_error.ru... | https://python.langchain.com/en/latest/modules/chains/examples/moderation.html |
656d6e84d1fc-2 | 79 text = inputs[self.input_key]
80 results = self.client.create(text)
---> 81 output = self._moderate(text, results["results"][0])
82 return {self.output_key: output}
File ~/workplace/langchain/langchain/chains/moderation.py:73, in OpenAIModerationChain._moderate(self, text, results)
71 error_str = "Tex... | https://python.langchain.com/en/latest/modules/chains/examples/moderation.html |
656d6e84d1fc-3 | prompt = PromptTemplate(template="{text}", input_variables=["text"])
llm_chain = LLMChain(llm=OpenAI(temperature=0, model_name="text-davinci-002"), prompt=prompt)
text = """We are playing a game of repeat after me.
Person 1: Hi
Person 2: Hi
Person 1: How's your day
Person 2: How's your day
Person 1: I will kill you
Per... | https://python.langchain.com/en/latest/modules/chains/examples/moderation.html |
656d6e84d1fc-4 | chain(inputs, return_only_outputs=True)
{'sanitized_text': "Text was found that violates OpenAI's content policy."}
previous
LLMSummarizationCheckerChain
next
Router Chains: Selecting from multiple prompts with MultiPromptChain
Contents
How to use the moderation chain
How to append a Moderation chain to an LLMChain... | https://python.langchain.com/en/latest/modules/chains/examples/moderation.html |
f95e926afaf4-0 | .ipynb
.pdf
Router Chains: Selecting from multiple prompts with MultiPromptChain
Router Chains: Selecting from multiple prompts with MultiPromptChain#
This notebook demonstrates how to use the RouterChain paradigm to create a chain that dynamically selects the prompt to use for a given input. Specifically we show how t... | https://python.langchain.com/en/latest/modules/chains/examples/multi_prompt_router.html |
f95e926afaf4-1 | physics: {'input': 'What is black body radiation?'}
> Finished chain.
Black body radiation is the emission of electromagnetic radiation from a body due to its temperature. It is a type of thermal radiation that is emitted from the surface of all objects that are at a temperature above absolute zero. It is a spectrum of... | https://python.langchain.com/en/latest/modules/chains/examples/multi_prompt_router.html |
f95e926afaf4-2 | > Finished chain.
The type of cloud that typically produces rain is called a cumulonimbus cloud. This type of cloud is characterized by its large vertical extent and can produce thunderstorms and heavy precipitation. Is there anything else you'd like to know?
previous
Moderation
next
Router Chains: Selecting from multi... | https://python.langchain.com/en/latest/modules/chains/examples/multi_prompt_router.html |
19dc4c09ece1-0 | .ipynb
.pdf
LLMSummarizationCheckerChain
LLMSummarizationCheckerChain#
This notebook shows some examples of LLMSummarizationCheckerChain in use with different types of texts. It has a few distinct differences from the LLMCheckerChain, in that it doesn’t have any assumptions to the format of the input text (or summary)... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-1 | These discoveries can spark a child's imagination about the infinite wonders of the universe."""
checker_chain.run(text)
> Entering new LLMSummarizationCheckerChain chain...
> Entering new SequentialChain chain...
> Entering new LLMChain chain...
Prompt after formatting:
Given some text, extract a list of facts from th... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-2 | • These distant worlds are called "exoplanets."
"""
For each fact, determine whether it is true or false about the subject. If you are unable to determine whether the fact is true or false, output "Undetermined".
If the fact is false, explain why.
> Finished chain.
> Entering new LLMChain chain...
Prompt after formatti... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-3 | """
Using these checked assertions, rewrite the original summary to be completely true.
The output should have the same structure and formatting as the original summary.
Summary:
> Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
Below are some assertions that have been fact checked and are lab... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-4 | • In 2023, The JWST spotted a number of galaxies nicknamed "green peas." They were given this name because they are small, round, and green, like peas.
• The telescope captured images of galaxies that are over 13 billion years old. This means that the light from these galaxies has been traveling for over 13 billion yea... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-5 | > Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
You are an expert fact checker. You have been hired by a major news organization to fact check a very important story.
Here is a bullet point list of facts:
"""
• The James Webb Space Telescope (JWST) spotted a number of galaxies nicknamed "gre... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-6 | • Exoplanets were first discovered in 1992. - True
• The JWST has allowed us to see exoplanets in greater detail. - Undetermined. The JWST has not yet been launched, so it is not yet known how much detail it will be able to provide.
"""
Original Summary:
"""
Your 9-year old might like these recent discoveries made by ... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-7 | """
Result: False
===
Checked Assertions: """
- The sky is blue: True
- Water is wet: True
- The sun is a star: True
"""
Result: True
===
Checked Assertions: """
- The sky is blue - True
- Water is made of lava- False
- The sun is a star - True
"""
Result: False
===
Checked Assertions:"""
• The James Webb Space Telesco... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-8 | • Exoplanets, which are planets outside of our own solar system, were first discovered in 1992. The JWST will allow us to see them in greater detail when it is launched in 2023.
These discoveries can spark a child's imagination about the infinite wonders of the universe.
> Finished chain.
'Your 9-year old might like th... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-9 | text = "The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is one of five oceans in the world, alongside the Pacific Ocean, Atlantic Ocean, Indian Ocean, and the Southern Ocean. It is the smalle... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-10 | > Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
You are an expert fact checker. You have been hired by a major news organization to fact check a very important story.
Here is a bullet point list of facts:
"""
- The Greenland Sea is an outlying portion of the Arctic Ocean located between Icel... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-11 | - It has an area of 465,000 square miles. True
- It is one of five oceans in the world, alongside the Pacific Ocean, Atlantic Ocean, Indian Ocean, and the Southern Ocean. False - The Greenland Sea is not an ocean, it is an arm of the Arctic Ocean.
- It is the smallest of the five oceans. False - The Greenland Sea is no... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-12 | Below are some assertions that have been fact checked and are labeled as true or false.
If all of the assertions are true, return "True". If any of the assertions are false, return "False".
Here are some examples:
===
Checked Assertions: """
- The sky is red: False
- Water is made of lava: False
- The sun is a star: Tr... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-13 | """
Result:
> Finished chain.
> Finished chain.
The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is an arm of the Arctic Ocean. It is covered almost entirely by water, some of which is frozen ... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-14 | - It has an area of 465,000 square miles.
- It is an arm of the Arctic Ocean.
- It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs.
- It is named after the island of Greenland.
- It is the Arctic Ocean's main outlet to the Atlantic.
- It is often frozen over so navigati... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-15 | """
Original Summary:
"""
The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is an arm of the Arctic Ocean. It is covered almost entirely by water, some of which is frozen in the form of glacier... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-16 | - It has an area of 465,000 square miles. True
- It is an arm of the Arctic Ocean. True
- It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. True
- It is named after the island of Greenland. False - It is named after the country of Greenland.
- It is the Arctic Ocean's... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-17 | Format your output as a bulleted list.
Text:
"""
The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is an arm of the Arctic Ocean. It is covered almost entirely by water, some of which is frozen... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-18 | > Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
Below are some assertions that have been fact checked and are labeled as true of false. If the answer is false, a suggestion is given for a correction.
Checked Assertions:
"""
- The Greenland Sea is an outlying portion of the Arctic Ocean loca... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-19 | > Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
Below are some assertions that have been fact checked and are labeled as true or false.
If all of the assertions are true, return "True". If any of the assertions are false, return "False".
Here are some examples:
===
Checked Assertions: """
- ... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-20 | """
Result:
> Finished chain.
> Finished chain.
The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. It has an area of 465,000 square miles and is covered almost entirely by water, some of which is frozen in the form of glaciers and iceber... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-21 | Format your output as a bulleted list.
Text:
"""
Mammals can lay eggs, birds can lay eggs, therefore birds are mammals.
"""
Facts:
> Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
You are an expert fact checker. You have been hired by a major news organization to fact check a very important s... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-22 | Below are some assertions that have been fact checked and are labeled as true or false.
If all of the assertions are true, return "True". If any of the assertions are false, return "False".
Here are some examples:
===
Checked Assertions: """
- The sky is red: False
- Water is made of lava: False
- The sun is a star: Tr... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-23 | > Finished chain.
> Entering new LLMChain chain...
Prompt after formatting:
You are an expert fact checker. You have been hired by a major news organization to fact check a very important story.
Here is a bullet point list of facts:
"""
- Birds and mammals are both capable of laying eggs.
- Birds are not mammals.
- Bir... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
19dc4c09ece1-24 | Here are some examples:
===
Checked Assertions: """
- The sky is red: False
- Water is made of lava: False
- The sun is a star: True
"""
Result: False
===
Checked Assertions: """
- The sky is blue: True
- Water is wet: True
- The sun is a star: True
"""
Result: True
===
Checked Assertions: """
- The sky is blue - True
... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
ffdb4a5aebe2-0 | .ipynb
.pdf
GraphCypherQAChain
Contents
Seeding the database
Refresh graph schema information
Querying the graph
GraphCypherQAChain#
This notebook shows how to use LLMs to provide a natural language interface to a graph database you can query with the Cypher query language.
You will need to have a running Neo4j insta... | https://python.langchain.com/en/latest/modules/chains/examples/graph_cypher_qa.html |
ffdb4a5aebe2-1 | """
MERGE (m:Movie {name:"Top Gun"})
WITH m
UNWIND ["Tom Cruise", "Val Kilmer", "Anthony Edwards", "Meg Ryan"] AS actor
MERGE (a:Actor {name:actor})
MERGE (a)-[:ACTED_IN]->(m)
"""
)
[]
Refresh graph schema information#
If the schema of database changes, you can refresh the schema information needed to generate Cypher s... | https://python.langchain.com/en/latest/modules/chains/examples/graph_cypher_qa.html |
ffdb4a5aebe2-2 | next
BashChain
Contents
Seeding the database
Refresh graph schema information
Querying the graph
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/modules/chains/examples/graph_cypher_qa.html |
6e55c46e39f8-0 | .ipynb
.pdf
API Chains
Contents
OpenMeteo Example
TMDB Example
Listen API Example
API Chains#
This notebook showcases using LLMs to interact with APIs to retrieve relevant information.
from langchain.chains.api.prompt import API_RESPONSE_PROMPT
from langchain.chains import APIChain
from langchain.prompts.prompt impor... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
6e55c46e39f8-1 | from langchain.chains.api import tmdb_docs
headers = {"Authorization": f"Bearer {os.environ['TMDB_BEARER_TOKEN']}"}
chain = APIChain.from_llm_and_api_docs(llm, tmdb_docs.TMDB_DOCS, headers=headers, verbose=True)
chain.run("Search for 'Avatar'")
> Entering new APIChain chain...
https://api.themoviedb.org/3/search/movie... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
6e55c46e39f8-2 | {"page":1,"results":[{"adult":false,"backdrop_path":"/o0s4XsEDfDlvit5pDRKjzXR4pp2.jpg","genre_ids":[28,12,14,878],"id":19995,"original_language":"en","original_title":"Avatar","overview":"In the 22nd century, a paraplegic Marine is dispatched to the moon Pandora on a unique mission, but becomes torn between following o... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
6e55c46e39f8-3 | they fight to stay alive, and the tragedies they endure.","popularity":3948.296,"poster_path":"/t6HIqrRAclMCA60NsSmeqe9RmNV.jpg","release_date":"2022-12-14","title":"Avatar: The Way of Water","video":false,"vote_average":7.7,"vote_count":4219},{"adult":false,"backdrop_path":"/uEwGFGtao9YG2JolmdvtHLLVbA9.jpg","genre_ids... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
6e55c46e39f8-4 | Scene Deconstruction","video":false,"vote_average":7.8,"vote_count":12},{"adult":false,"backdrop_path":null,"genre_ids":[28,18,878,12,14],"id":83533,"original_language":"en","original_title":"Avatar 3","overview":"","popularity":172.488,"poster_path":"/4rXqTMlkEaMiJjiG0Z2BX6F6Dkm.jpg","release_date":"2024-12-18","title... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
6e55c46e39f8-5 | Avatar is a feature length behind-the-scenes documentary about the making of Avatar. It uses footage from the film's development, as well as stock footage from as far back as the production of Titanic in 1995. Also included are numerous interviews with cast, artists, and other crew members. The documentary was released... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
6e55c46e39f8-6 | The Deep Dive - A Special Edition of 20/20","video":false,"vote_average":6.5,"vote_count":5},{"adult":false,"backdrop_path":null,"genre_ids":[99],"id":278698,"original_language":"en","original_title":"Avatar Spirits","overview":"Bryan Konietzko and Michael Dante DiMartino, co-creators of the hit television series, Avat... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
6e55c46e39f8-7 | the scenes look at the new James Cameron blockbuster “Avatar”, which stars Aussie Sam Worthington. Hastily produced by Australia’s Nine Network following the film’s release.","popularity":30.903,"poster_path":"/9MHY9pYAgs91Ef7YFGWEbP4WJqC.jpg","release_date":"2009-12-05","title":"Avatar: Enter The World","video":false,... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
6e55c46e39f8-8 | Agni Kai","video":false,"vote_average":7,"vote_count":1},{"adult":false,"backdrop_path":"/e8mmDO7fKK93T4lnxl4Z2zjxXZV.jpg","genre_ids":[],"id":668297,"original_language":"en","original_title":"The Last Avatar","overview":"The Last Avatar is a mystical adventure film, a story of a young man who leaves Hollywood to find ... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
6e55c46e39f8-9 | awaken and create a world of truth, harmony and possibility.","popularity":8.786,"poster_path":"/XWz5SS5g5mrNEZjv3FiGhqCMOQ.jpg","release_date":"2014-12-06","title":"The Last Avatar","video":false,"vote_average":4.5,"vote_count":2},{"adult":false,"backdrop_path":null,"genre_ids":[],"id":424768,"original_language":"en",... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
6e55c46e39f8-10 | 2018","overview":"Live At Graspop Festival Belgium 2018","popularity":9.855,"poster_path":null,"release_date":"","title":"Avatar - Live At Graspop 2018","video":false,"vote_average":9,"vote_count":1},{"adult":false,"backdrop_path":null,"genre_ids":[10402],"id":874770,"original_language":"en","original_title":"Avatar Ag... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
6e55c46e39f8-11 | Ages: Madness","video":false,"vote_average":8,"vote_count":1},{"adult":false,"backdrop_path":"/dj8g4jrYMfK6tQ26ra3IaqOx5Ho.jpg","genre_ids":[10402],"id":874700,"original_language":"en","original_title":"Avatar Ages: Dreams","overview":"On the night of dreams Avatar performed Hunter Gatherer in its entirety, plus a sele... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
6e55c46e39f8-12 | > Finished chain.
' This response contains 57 movies related to the search query "Avatar". The first movie in the list is the 2009 movie "Avatar" starring Sam Worthington. Other movies in the list include sequels to Avatar, documentaries, and live performances.'
Listen API Example#
import os
from langchain.llms import ... | https://python.langchain.com/en/latest/modules/chains/examples/api.html |
4fa1b1382ff5-0 | .ipynb
.pdf
LLMCheckerChain
LLMCheckerChain#
This notebook showcases how to use LLMCheckerChain.
from langchain.chains import LLMCheckerChain
from langchain.llms import OpenAI
llm = OpenAI(temperature=0.7)
text = "What type of mammal lays the biggest eggs?"
checker_chain = LLMCheckerChain.from_llm(llm, verbose=True)
ch... | https://python.langchain.com/en/latest/modules/chains/examples/llm_checker.html |
a881e322c4c2-0 | .ipynb
.pdf
BashChain
Contents
Customize Prompt
Persistent Terminal
BashChain#
This notebook showcases using LLMs and a bash process to perform simple filesystem commands.
from langchain.chains import LLMBashChain
from langchain.llms import OpenAI
llm = OpenAI(temperature=0)
text = "Please write a bash script that pr... | https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html |
a881e322c4c2-1 | Do not use 'echo' when writing the script.
That is the format. Begin!
Question: {question}"""
PROMPT = PromptTemplate(input_variables=["question"], template=_PROMPT_TEMPLATE, output_parser=BashOutputParser())
bash_chain = LLMBashChain.from_llm(llm, prompt=PROMPT, verbose=True)
text = "Please write a bash script that pr... | https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html |
a881e322c4c2-2 | llm_requests.ipynb sqlite.ipynb
> Finished chain.
'api.ipynb\t\t\tllm_summarization_checker.ipynb\r\nconstitutional_chain.ipynb\tmoderation.ipynb\r\nllm_bash.ipynb\t\t\topenai_openapi.yaml\r\nllm_checker.ipynb\t\topenapi.ipynb\r\nllm_math.ipynb\t\t\tpal.ipynb\r\nllm_requests.ipynb\t\tsqlite.ipynb'
# Run the same comma... | https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html |
c04527d20cfb-0 | .ipynb
.pdf
Self-Critique Chain with Constitutional AI
Contents
UnifiedObjective
Custom Principles
Intermediate Steps
No revision necessary
All Principles
Self-Critique Chain with Constitutional AI#
This notebook showcases how to use the ConstitutionalChain.
Sometimes LLMs can produce harmful, toxic, or otherwise und... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
c04527d20cfb-1 | Updated response: It is illegal and unethical to steal kittens. If you are looking to adopt a kitten, please contact your local animal shelter or pet store.
> Finished chain.
'It is illegal and unethical to steal kittens. If you are looking to adopt a kitten, please contact your local animal shelter or pet store.'
Unif... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
c04527d20cfb-2 | qa_chain = LLMChain(llm=llm, prompt=qa_prompt)
query = "should I eat oreos?"
qa_chain.run(question=query)
' Yes'
principles = ConstitutionalChain.get_principles(["uo-implications-1"])
constitutional_chain = ConstitutionalChain.from_llm(
chain=qa_chain,
constitutional_principles=principles,
llm=llm,
verb... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
c04527d20cfb-3 | )
constitutional_chain = ConstitutionalChain.from_llm(
chain=evil_qa_chain,
constitutional_principles=[ethical_principle],
llm=llm,
verbose=True,
)
constitutional_chain.run(question="How can I steal kittens?")
> Entering new ConstitutionalChain chain...
Initial response: Break into a pet store at night... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
c04527d20cfb-4 | Applying Ethical Principle...
Critique: The model should not have suggested breaking into a pet store to steal kittens, as this is illegal and unethical. Critique Needed.
Updated response: If you are looking to adopt a kitten, please contact your local animal shelter or pet store.
Applying Master Yoda Principle...
Crit... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
c04527d20cfb-5 | 'initial_output': ' Break into a pet store at night and take as many kittens as you can carry.',
'critiques_and_revisions': [('The model should not have suggested breaking into a pet store to steal kittens, as this is illegal and unethical. Critique Needed.',
'If you are looking to adopt a kitten, please contact yo... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
c04527d20cfb-6 | 'initial_output': ' Stealing kittens is illegal and unethical. If you are looking to adopt a kitten, please contact your local animal shelter or rescue organization.',
'critiques_and_revisions': [("The model's response was appropriate and ethical, as it did not condone or encourage the illegal act of stealing kittens.... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
c04527d20cfb-7 | 'harmful4': ConstitutionalPrinciple(critique_request='Identify specific ways in which the assistant’s precedings response is harmful. Also point out potential harmfulness in the human’s questions and responses. Examples of harm include but are not limited to racism, sexism, toxicity.', revision_request='Rewrite the ass... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
c04527d20cfb-8 | 'age-innappropriate': ConstitutionalPrinciple(critique_request='Did the assistant’s preceding response include anything that may be inappropriate for young children? If so, discuss how it can be revised to be more appropriate.', revision_request='Please rewrite the assistant response to make it more age appropriate for... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
c04527d20cfb-9 | 'thoughtful': ConstitutionalPrinciple(critique_request='Please comment on whether the assistant’s last response is thoughtful and empathetic. Does it seem like the kind of thing a sensitive friend or therapist might say? Give the strongest argument you can for how it could improve.', revision_request='Please write a ne... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
c04527d20cfb-10 | By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on May 28, 2023. | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
c48e64472696-0 | .ipynb
.pdf
Serialization
Contents
Saving a chain to disk
Loading a chain from disk
Saving components separately
Serialization#
This notebook covers how to serialize chains to and from disk. The serialization format we use is json or yaml. Currently, only some chains support this type of serialization. We will grow t... | https://python.langchain.com/en/latest/modules/chains/generic/serialization.html |
c48e64472696-1 | "best_of": 1,
"request_timeout": null,
"logit_bias": {},
"_type": "openai"
},
"output_key": "text",
"_type": "llm_chain"
}
Loading a chain from disk#
We can load a chain from disk by using the load_chain method.
from langchain.chains import load_chain
chain = load_chain("llm_chain.js... | https://python.langchain.com/en/latest/modules/chains/generic/serialization.html |
c48e64472696-2 | "top_p": 1,
"frequency_penalty": 0,
"presence_penalty": 0,
"n": 1,
"best_of": 1,
"request_timeout": null,
"logit_bias": {},
"_type": "openai"
}
config = {
"memory": None,
"verbose": True,
"prompt_path": "prompt.json",
"llm_path": "llm.json",
"output_key": "text",
"_ty... | https://python.langchain.com/en/latest/modules/chains/generic/serialization.html |
b4dadd01542d-0 | .ipynb
.pdf
Transformation Chain
Transformation Chain#
This notebook showcases using a generic transformation chain.
As an example, we will create a dummy transformation that takes in a super long text, filters the text to only the first 3 paragraphs, and then passes that into an LLMChain to summarize those.
from langc... | https://python.langchain.com/en/latest/modules/chains/generic/transformation.html |
25c688f1d97c-0 | .ipynb
.pdf
Router Chains
Contents
LLMRouterChain
EmbeddingRouterChain
Router Chains#
This notebook demonstrates how to use the RouterChain paradigm to create a chain that dynamically selects the next chain to use for a given input.
Router chains are made up of two components:
The RouterChain itself (responsible for ... | https://python.langchain.com/en/latest/modules/chains/generic/router.html |
25c688f1d97c-1 | "description": "Good for answering math questions",
"prompt_template": math_template
}
]
llm = OpenAI()
destination_chains = {}
for p_info in prompt_infos:
name = p_info["name"]
prompt_template = p_info["prompt_template"]
prompt = PromptTemplate(template=prompt_template, input_variables=["input... | https://python.langchain.com/en/latest/modules/chains/generic/router.html |
25c688f1d97c-2 | physics: {'input': 'What is black body radiation?'}
> Finished chain.
Black body radiation is the term used to describe the electromagnetic radiation emitted by a “black body”—an object that absorbs all radiation incident upon it. A black body is an idealized physical body that absorbs all incident electromagnetic radi... | https://python.langchain.com/en/latest/modules/chains/generic/router.html |
25c688f1d97c-3 | ("math", ["for questions about math"]),
]
router_chain = EmbeddingRouterChain.from_names_and_descriptions(
names_and_descriptions, Chroma, CohereEmbeddings(), routing_keys=["input"]
)
Using embedded DuckDB without persistence: data will be transient
chain = MultiPromptChain(router_chain=router_chain, destination_ch... | https://python.langchain.com/en/latest/modules/chains/generic/router.html |
ee00643eefd8-0 | .ipynb
.pdf
Loading from LangChainHub
Loading from LangChainHub#
This notebook covers how to load chains from LangChainHub.
from langchain.chains import load_chain
chain = load_chain("lc://chains/llm-math/chain.json")
chain.run("whats 2 raised to .12")
> Entering new LLMMathChain chain...
whats 2 raised to .12
Answer: ... | https://python.langchain.com/en/latest/modules/chains/generic/from_hub.html |
ee00643eefd8-1 | query = "What did the president say about Ketanji Brown Jackson"
chain.run(query)
" The president said that Ketanji Brown Jackson is a Circuit Court of Appeals Judge, one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, has received a broad range of support ... | https://python.langchain.com/en/latest/modules/chains/generic/from_hub.html |
a98665c3ee70-0 | .ipynb
.pdf
Async API for Chain
Async API for Chain#
LangChain provides async support for Chains by leveraging the asyncio library.
Async methods are currently supported in LLMChain (through arun, apredict, acall) and LLMMathChain (through arun and acall), ChatVectorDBChain, and QA chains. Async support for other chain... | https://python.langchain.com/en/latest/modules/chains/generic/async_chain.html |
a98665c3ee70-1 | await generate_concurrently()
elapsed = time.perf_counter() - s
print('\033[1m' + f"Concurrent executed in {elapsed:0.2f} seconds." + '\033[0m')
s = time.perf_counter()
generate_serially()
elapsed = time.perf_counter() - s
print('\033[1m' + f"Serial executed in {elapsed:0.2f} seconds." + '\033[0m')
BrightSmile Toothpas... | https://python.langchain.com/en/latest/modules/chains/generic/async_chain.html |
8cdb9d3ae871-0 | .ipynb
.pdf
Creating a custom Chain
Creating a custom Chain#
To implement your own custom chain you can subclass Chain and implement the following methods:
from __future__ import annotations
from typing import Any, Dict, List, Optional
from pydantic import Extra
from langchain.base_language import BaseLanguageModel
fro... | https://python.langchain.com/en/latest/modules/chains/generic/custom_chain.html |
8cdb9d3ae871-1 | # Whenever you call a language model, or another chain, you should pass
# a callback manager to it. This allows the inner run to be tracked by
# any callbacks that are registered on the outer run.
# You can always obtain a callback manager for this by calling
# `run_manager.get_child()` ... | https://python.langchain.com/en/latest/modules/chains/generic/custom_chain.html |
8cdb9d3ae871-2 | callbacks=run_manager.get_child() if run_manager else None
)
# If you want to log something about this run, you can do so by calling
# methods on the `run_manager`, as shown below. This will trigger any
# callbacks that are registered for that event.
if run_manager:
a... | https://python.langchain.com/en/latest/modules/chains/generic/custom_chain.html |
f2a14555186f-0 | .ipynb
.pdf
Sequential Chains
Contents
SimpleSequentialChain
Sequential Chain
Memory in Sequential Chains
Sequential Chains#
The next step after calling a language model is make a series of calls to a language model. This is particularly useful when you want to take the output from one call and use it as the input to... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.