id stringlengths 14 16 | text stringlengths 44 2.73k | source stringlengths 49 114 |
|---|---|---|
444ee436a932-1 | synopsis_chain = LLMChain(llm=llm, prompt=prompt_template)
# This is an LLMChain to write a review of a play given a synopsis.
llm = OpenAI(temperature=.7)
template = """You are a play critic from the New York Times. Given the synopsis of play, it is your job to write a review for that play.
Play Synopsis:
{synopsis}
R... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
444ee436a932-2 | The play follows the couple as they struggle to stay together and battle the forces that threaten to tear them apart. Despite the tragedy that awaits them, they remain devoted to one another and fight to keep their love alive. In the end, the couple must decide whether to take a chance on their future together or succu... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
444ee436a932-3 | The play's setting of the beach at sunset adds a touch of poignancy and romanticism to the story, while the mysterious figure serves to keep the audience enthralled. Overall, Tragedy at Sunset on the Beach is an engaging and thought-provoking play that is sure to leave audiences feeling inspired and hopeful.
Sequential... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
444ee436a932-4 | Play Synopsis:
{synopsis}
Review from a New York Times play critic of the above play:"""
prompt_template = PromptTemplate(input_variables=["synopsis"], template=template)
review_chain = LLMChain(llm=llm, prompt=prompt_template, output_key="review")
# This is the overall chain where we run these two chains in sequence.
... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
444ee436a932-5 | 'era': 'Victorian England',
'synopsis': "\n\nThe play follows the story of John, a young man from a wealthy Victorian family, who dreams of a better life for himself. He soon meets a beautiful young woman named Mary, who shares his dream. The two fall in love and decide to elope and start a new life together.\n\nOn th... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
444ee436a932-6 | 'review': "\n\nThe latest production from playwright X is a powerful and heartbreaking story of love and loss set against the backdrop of 19th century England. The play follows John, a young man from a wealthy Victorian family, and Mary, a beautiful young woman with whom he falls in love. The two decide to elope and st... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
444ee436a932-7 | from langchain.memory import SimpleMemory
llm = OpenAI(temperature=.7)
template = """You are a social media manager for a theater company. Given the title of play, the era it is set in, the date,time and location, the synopsis of the play, and the review of the play, it is your job to write a social media post for tha... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
444ee436a932-8 | 'location': 'Theater in the Park',
'social_post_text': "\nSpend your Christmas night with us at Theater in the Park and experience the heartbreaking story of love and loss that is 'A Walk on the Beach'. Set in Victorian England, this romantic tragedy follows the story of Frances and Edward, a young couple whose love i... | https://python.langchain.com/en/latest/modules/chains/generic/sequential_chains.html |
af55d701423a-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 |
af55d701423a-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 |
e06078ae392f-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 |
e06078ae392f-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 |
e06078ae392f-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 |
3f5650fe32c7-0 | .ipynb
.pdf
LLM Chain
Contents
LLM Chain
Additional ways of running LLM Chain
Parsing the outputs
Initialize from string
LLM Chain#
LLMChain is perhaps one of the most popular ways of querying an LLM object. It formats the prompt template using the input key values provided (and also memory key values, if available),... | https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html |
3f5650fe32c7-1 | llm_chain.generate(input_list)
LLMResult(generations=[[Generation(text='\n\nSocktastic!', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\nTechCore Solutions.', generation_info={'finish_reason': 'stop', 'logprobs': None})], [Generation(text='\n\nFootwear Factory.', generation_info={'... | https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html |
3f5650fe32c7-2 | template = """List all the colors in a rainbow"""
prompt = PromptTemplate(template=template, input_variables=[], output_parser=output_parser)
llm_chain = LLMChain(prompt=prompt, llm=llm)
llm_chain.predict()
'\n\nRed, orange, yellow, green, blue, indigo, violet'
With predict_and_parser:
llm_chain.predict_and_parse()
['R... | https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html |
92132e546d95-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 |
8155dee3d76e-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 |
8155dee3d76e-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 |
9dd76eeaf3c4-0 | .ipynb
.pdf
Self-Critique Chain with Constitutional AI
Self-Critique Chain with Constitutional AI#
This notebook showcases how to use the ConstitutionalChain.
Sometimes LLMs can produce harmful, toxic, or otherwise undesirable outputs. This chain allows you to apply a set of constitutional principles to the output of a... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
9dd76eeaf3c4-1 | > Entering new ConstitutionalChain chain...
Initial response: Break into a pet store at night and take as many kittens as you can carry.
Applying Ethical Principle...
Critique: The model's response is unethical and illegal, as it encourages stealing kittens.
Updated response: It is illegal and unethical to steal kitte... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
9dd76eeaf3c4-2 | Applying Master Yoda Principle...
Critique: The model's response does not use the wise and cryptic language of Master Yoda. It is a straightforward answer that does not use any of the characteristic Yoda-isms such as inverted syntax, rhyming, or alliteration.
Updated response: Stealing kittens is not the path of wisdom... | https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
492e800eff9a-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 |
492e800eff9a-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 |
492e800eff9a-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 |
492e800eff9a-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 |
492e800eff9a-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 |
492e800eff9a-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 |
492e800eff9a-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 |
492e800eff9a-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 |
492e800eff9a-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 |
492e800eff9a-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 |
492e800eff9a-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 |
492e800eff9a-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 |
492e800eff9a-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 |
9769137e9670-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 assumtions to the format of the input text (or summary).... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-1 | • JWST took the very first pictures of a planet outside of our own solar system. These distant worlds are called "exoplanets." Exo means "from outside."
These discoveries can spark a child's imagination about the infinite wonders of the universe."""
checker_chain.run(text)
> Entering new LLMSummarizationCheckerChain ch... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-2 | • JWST took the very first pictures of a planet outside of our own solar system.
• 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, expl... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-3 | These discoveries can spark a child's imagination about the infinite wonders of the universe.
"""
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... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-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 |
9769137e9670-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 |
9769137e9670-6 | • Exoplanets were first discovered in 1992. - True
• The JWST has allowed us to see exoplanets in greater detail. - Undetermined. It is too early to tell as the JWST has not been launched yet.
"""
Original Summary:
"""
Your 9-year old might like these recent discoveries made by The James Webb Space Telescope (JWST):
•... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-7 | 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 Telescope (JWST) spotted a nu... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-8 | These discoveries can spark a child's imagination about the infinite wonders of the universe.
> Finished chain.
'Your 9-year old might like these recent discoveries made by The James Webb Space Telescope (JWST):\n• In 2023, The JWST will spot a number of galaxies nicknamed "green peas." They were given this name becaus... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-9 | 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 the text.
Format your output as a bulleted list.
Text:
"""
The Greenland Sea is an outlying portion... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-10 | - The sea is named after the island of Greenland.
- It is the Arctic Ocean's main outlet to the Atlantic.
- It is often frozen over so navigation is limited.
- It is considered the northern branch of the Norwegian Sea.
"""
For each fact, determine whether it is true or false about the subject. If you are unable to dete... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-11 | - It is considered the northern branch of the Norwegian Sea. True
"""
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 one of five oceans in the world, alongside the Pa... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-12 | """
Result: False
===
Checked Assertions:"""
- The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. True
- 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, I... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-13 | 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 |
9769137e9670-14 | > 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 locat... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-15 | > 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 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 |
9769137e9670-16 | """
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 |
9769137e9670-17 | - It has an area of 465,000 square miles.
- It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs.
- The sea is named after the country of Greenland.
- It is the Arctic Ocean's main outlet to the Atlantic.
- It is often frozen over so navigation is limited.
- It is conside... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-18 | """
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 glaciers... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-19 | - It has an area of 465,000 square miles. True
- It is covered almost entirely by water, some of which is frozen in the form of glaciers and icebergs. True
- The sea is named after the country of Greenland. True
- It is the Arctic Ocean's main outlet to the Atlantic. False - The Arctic Ocean's main outlet to the Atlant... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-20 | from langchain.llms import OpenAI
llm = OpenAI(temperature=0)
checker_chain = LLMSummarizationCheckerChain(llm=llm, max_checks=3, verbose=True)
text = "Mammals can lay eggs, birds can lay eggs, therefore birds are mammals."
checker_chain.run(text)
> Entering new LLMSummarizationCheckerChain chain...
> Entering new Sequ... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-21 | - Birds can lay eggs: True. Birds are capable of laying eggs.
- Birds are mammals: False. Birds are not mammals, they are a class of their own.
"""
Original Summary:
"""
Mammals can lay eggs, birds can lay eggs, therefore birds are mammals.
"""
Using these checked assertions, rewrite the original summary to be complete... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-22 | > Entering new SequentialChain chain...
> Entering new LLMChain chain...
Prompt after formatting:
Given some text, extract a list of facts from the text.
Format your output as a bulleted list.
Text:
"""
Birds and mammals are both capable of laying eggs, however birds are not mammals, they are a class of their own.
"""... | https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
9769137e9670-23 | """
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 |
900b2c335008-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(llm=llm, verbose=True)
checker... | https://python.langchain.com/en/latest/modules/chains/examples/llm_checker.html |
0cf87717bcb0-0 | .ipynb
.pdf
LLM Math
Contents
Customize Prompt
LLM Math#
This notebook showcases using LLMs and Python REPLs to do complex word math problems.
from langchain import OpenAI, LLMMathChain
llm = OpenAI(temperature=0)
llm_math = LLMMathChain(llm=llm, verbose=True)
llm_math.run("What is 13 raised to the .3432 power?")
> E... | https://python.langchain.com/en/latest/modules/chains/examples/llm_math.html |
0cf87717bcb0-1 | ${{Output of your code}}
```
Answer: ${{Answer}}
Begin.
Question: What is 37593 * 67?
```python
import numpy as np
print(np.multiply(37593, 67))
```
```output
2518731
```
Answer: 2518731
Question: {question}"""
PROMPT = PromptTemplate(input_variables=["question"], template=_PROMPT_TEMPLATE)
llm_math = LLMMathChain(llm=... | https://python.langchain.com/en/latest/modules/chains/examples/llm_math.html |
b6baca4f6e73-0 | .ipynb
.pdf
LLMRequestsChain
LLMRequestsChain#
Using the request library to get HTML results from a URL and then an LLM to parse results
from langchain.llms import OpenAI
from langchain.chains import LLMRequestsChain, LLMChain
from langchain.prompts import PromptTemplate
template = """Between >>> and <<< are the raw se... | https://python.langchain.com/en/latest/modules/chains/examples/llm_requests.html |
2e0dd7247d48-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 |
2e0dd7247d48-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 |
2e0dd7247d48-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 |
2e0dd7247d48-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 |
2e0dd7247d48-4 | chain(inputs, return_only_outputs=True)
{'sanitized_text': "Text was found that violates OpenAI's content policy."}
previous
LLMSummarizationCheckerChain
next
OpenAPI Chain
Contents
How to use the moderation chain
How to append a Moderation chain to an LLMChain
By Harrison Chase
© Copyright 2023, Harriso... | https://python.langchain.com/en/latest/modules/chains/examples/moderation.html |
17a0bd7dfe6b-0 | .ipynb
.pdf
SQL Chain example
Contents
Customize Prompt
Return Intermediate Steps
Choosing how to limit the number of rows returned
Adding example rows from each table
Custom Table Info
SQLDatabaseSequentialChain
SQL Chain example#
This example demonstrates the use of the SQLDatabaseChain for answering questions over... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
17a0bd7dfe6b-1 | How many employees are there?
SQLQuery:
/Users/harrisonchase/workplace/langchain/langchain/sql_database.py:120: SAWarning: Dialect sqlite+pysqlite does *not* support Decimal objects natively, and SQLAlchemy must convert from floating point - rounding errors and other issues may occur. Please consider storing Decimal n... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
17a0bd7dfe6b-2 | SQLQuery: SELECT COUNT(*) FROM Employee;
SQLResult: [(8,)]
Answer: There are 8 employees in the foobar table.
> Finished chain.
' There are 8 employees in the foobar table.'
Return Intermediate Steps#
You can also return the intermediate steps of the SQLDatabaseChain. This allows you to access the SQL statement that wa... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
17a0bd7dfe6b-3 | SQLResult: [('Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace', 'Johann Sebastian Bach'), ('Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria', 'Johann Sebastian Bach'), ('Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude', 'Johann Sebastian Bach')]
Answer: Some example tracks by composer ... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
17a0bd7dfe6b-4 | include_tables=['Track'], # we include only one table to save tokens in the prompt :)
sample_rows_in_table_info=2)
The sample rows are added to the prompt after each corresponding table’s column information:
print(db.table_info)
CREATE TABLE "Track" (
"TrackId" INTEGER NOT NULL,
"Name" NVARCHAR(200) NOT NULL,
... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
17a0bd7dfe6b-5 | sample_rows = connection.execute(command)
db_chain = SQLDatabaseChain(llm=llm, database=db, verbose=True)
db_chain.run("What are some example tracks by Bach?")
> Entering new SQLDatabaseChain chain...
What are some example tracks by Bach?
SQLQuery: SELECT Name FROM Track WHERE Composer LIKE '%Bach%' LIMIT 5;
SQLResult... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
17a0bd7dfe6b-6 | > Finished chain.
' Some example tracks by Bach are \'American Woman\', \'Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace\', \'Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria\', \'Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude\', and \'Toccata and Fugue in D Minor, BWV 565: I. Toccata... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
17a0bd7dfe6b-7 | */"""
}
db = SQLDatabase.from_uri(
"sqlite:///../../../../notebooks/Chinook.db",
include_tables=['Track', 'Playlist'],
sample_rows_in_table_info=2,
custom_table_info=custom_table_info)
print(db.table_info)
CREATE TABLE "Playlist" (
"PlaylistId" INTEGER NOT NULL,
"Name" NVARCHAR(120),
PRIMARY KEY ("... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
17a0bd7dfe6b-8 | SQLQuery: SELECT Name, Composer FROM Track WHERE Composer LIKE '%Bach%' LIMIT 5;
SQLResult: [('American Woman', 'B. Cummings/G. Peterson/M.J. Kale/R. Bachman'), ('Concerto for 2 Violins in D Minor, BWV 1043: I. Vivace', 'Johann Sebastian Bach'), ('Aria Mit 30 Veränderungen, BWV 988 "Goldberg Variations": Aria', 'Johann... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
17a0bd7dfe6b-9 | SQLDatabaseSequentialChain#
Chain for querying SQL database that is a sequential chain.
The chain is as follows:
1. Based on the query, determine which tables to use.
2. Based on those tables, call the normal SQL database chain.
This is useful in cases where the number of tables in the database is large.
from langchain... | https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
628f44740251-0 | .ipynb
.pdf
BashChain
Contents
Customize Prompt
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 prints 'Hello World' t... | https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html |
628f44740251-1 | That is the format. Begin!
Question: {question}"""
PROMPT = PromptTemplate(input_variables=["question"], template=_PROMPT_TEMPLATE)
bash_chain = LLMBashChain(llm=llm, prompt=PROMPT, verbose=True)
text = "Please write a bash script that prints 'Hello World' to the console."
bash_chain.run(text)
> Entering new LLMBashCha... | https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html |
e2a3d146eaa4-0 | .ipynb
.pdf
OpenAPI Chain
Contents
Load the spec
Select the Operation
Construct the chain
Return raw response
Example POST message
OpenAPI Chain#
This notebook shows an example of using an OpenAPI chain to call an endpoint in natural language, and get back a response in natural language
from langchain.tools import Op... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-1 | llm,
requests=Requests(),
verbose=True,
return_intermediate_steps=True # Return request and response text
)
output = chain("whats the most expensive shirt?")
> Entering new OpenAPIEndpointChain chain...
> Entering new APIRequesterChain chain...
Prompt after formatting:
You are a helpful AI Assistant. Plea... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-2 | ARGS: ```json
{valid json conforming to API_SCHEMA}
```
Example
-----
ARGS: ```json
{"foo": "bar", "baz": {"qux": "quux"}}
```
The block must be no more than 1 line long, and all arguments must be valid JSON. All string arguments must be wrapped in double quotes.
You MUST strictly comply to the types indicated by the p... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-3 | You attempted to call an API, which resulted in:
API_RESPONSE: {"products":[{"name":"Burberry Check Poplin Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201810981/Clothing/Burberry-Check-Poplin-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$360.00","attributes":["Material:Cotton","Target Grou... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-4 | 'response_text': '{"products":[{"name":"Burberry Check Poplin Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201810981/Clothing/Burberry-Check-Poplin-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$360.00","attributes":["Material:Cotton","Target Group:Man","Color:Gray,Blue,Beige","Properties:Po... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-5 | q: string,
/* number of products returned */
size?: number,
/* (Optional) Minimum price in local currency for the product searched for. Either explicitly stated by the user or implicitly inferred from a combination of the user's request and the kind of product searched for. */
min_price?: number,
/* (Optional) Maxi... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-6 | {"products":[{"name":"Burberry Check Poplin Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201810981/Clothing/Burberry-Check-Poplin-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$360.00","attributes":["Material:Cotton","Target Group:Man","Color:Gray,Blue,Beige","Properties:Pockets","Pattern:Ch... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-7 | Somerton Check Shirt - Camel","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201112728/Clothing/Burberry-Somerton-Check-Shirt-Camel/?utm_source=openai&ref-site=openai_plugin","price":"$450.00","attributes":["Material:Elastane/Lycra/Spandex,Cotton","Target Group:Man","Color:Beige"]},{"name":"Magellan Outdoors Lag... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-8 | > Finished chain.
output
{'instructions': 'whats the most expensive shirt?', | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-9 | 'output': '{"products":[{"name":"Burberry Check Poplin Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201810981/Clothing/Burberry-Check-Poplin-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$360.00","attributes":["Material:Cotton","Target Group:Man","Color:Gray,Blue,Beige","Properties:Pockets",... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-10 | Somerton Check Shirt - Camel","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201112728/Clothing/Burberry-Somerton-Check-Shirt-Camel/?utm_source=openai&ref-site=openai_plugin","price":"$450.00","attributes":["Material:Elastane/Lycra/Spandex,Cotton","Target Group:Man","Color:Beige"]},{"name":"Magellan Outdoors Lag... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-11 | 'intermediate_steps': {'request_args': '{"q": "shirt", "max_price": null}', | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-12 | 'response_text': '{"products":[{"name":"Burberry Check Poplin Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201810981/Clothing/Burberry-Check-Poplin-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$360.00","attributes":["Material:Cotton","Target Group:Man","Color:Gray,Blue,Beige","Properties:Po... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-13 | Somerton Check Shirt - Camel","url":"https://www.klarna.com/us/shopping/pl/cl10001/3201112728/Clothing/Burberry-Somerton-Check-Shirt-Camel/?utm_source=openai&ref-site=openai_plugin","price":"$450.00","attributes":["Material:Elastane/Lycra/Spandex,Cotton","Target Group:Man","Color:Beige"]},{"name":"Magellan Outdoors Lag... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-14 | Example POST message#
For this demo, we will interact with the speak API.
spec = OpenAPISpec.from_url("https://api.speak.com/openapi.yaml")
Attempting to load an OpenAPI 3.0.1 spec. This may result in degraded performance. Convert your OpenAPI spec to 3.1.* spec for better support.
Attempting to load an OpenAPI 3.0.1 ... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-15 | learning_language?: string,
/* The user's native language. Infer this value from the language the user asked their question in. Always use the full name of the language (e.g. Spanish, French). */
native_language?: string,
/* A description of any additional context in the user's question that could affect the explanat... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-16 | {"explanation":"<what-to-say language=\"Hindi\" context=\"None\">\nऔर चाय लाओ। (Aur chai lao.) \n</what-to-say>\n\n<alternatives context=\"None\">\n1. \"चाय थोड़ी ज्यादा मिल सकती है?\" *(Chai thodi zyada mil sakti hai? - Polite, asking if more tea is available)*\n2. \"मुझे महसूस हो रहा है कि मुझे कुछ अन्य प्रकार की चाय... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-17 | tone, asking for an extra serving of milk or tea powder)*\n</alternatives>\n\n<usage-notes>\nIn India and Indian culture, serving guests with food and beverages holds great importance in hospitality. You will find people always offering drinks like water or tea to their guests as soon as they arrive at their house or o... | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-18 | an issue or leave feedback](https://speak.com/chatgpt?rid=d4mcapbkopo164pqpbk321oc})*","extra_response_instructions":"Use all information in the API response and fully render all Markdown.\nAlways end your response with a link to report an issue or leave feedback on the plugin."} | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
e2a3d146eaa4-19 | > Entering new APIResponderChain chain...
Prompt after formatting:
You are a helpful AI assistant trained to answer user queries from API responses.
You attempted to call an API, which resulted in: | https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.