id stringlengths 14 16 | text stringlengths 31 3.14k | source stringlengths 58 124 |
|---|---|---|
36e7b8c4770d-1 | {'text': '\n\nTechCore Solutions.'},
{'text': '\n\nFootwear Factory.'}]
generate is similar to apply, except it return an LLMResult instead of string. LLMResult often contains useful generation such as token usages and finish reason.
llm_chain.generate(input_list)
LLMResult(generations=[[Generation(text='\n\nSocktasti... | /content/https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html |
36e7b8c4770d-2 | prompt = PromptTemplate(template=template, input_variables=["adjective", "subject"])
llm_chain = LLMChain(prompt=prompt, llm=OpenAI(temperature=0))
llm_chain.predict(adjective="sad", subject="ducks")
'\n\nQ: What did the duck say when his friend died?\nA: Quack, quack, goodbye.'
Parsing the outputs#
By default, LLMChai... | /content/https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html |
36e7b8c4770d-3 | Initialize from string#
You can also construct an LLMChain from a string template directly.
template = """Tell me a {adjective} joke about {subject}."""
llm_chain = LLMChain.from_string(llm=llm, template=template)
llm_chain.predict(adjective="sad", subject="ducks")
'\n\nQ: What did the duck say when his friend died?\nA... | /content/https://python.langchain.com/en/latest/modules/chains/generic/llm_chain.html |
3d6ffef5a33e-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... | /content/https://python.langchain.com/en/latest/modules/chains/generic/transformation.html |
3d6ffef5a33e-1 | sequential_chain.run(state_of_the_union)
' The speaker addresses the nation, noting that while last year they were kept apart due to COVID-19, this year they are together again. They are reminded that regardless of their political affiliations, they are all Americans.'
previous
Serialization
next
Analyze Document
By Ha... | /content/https://python.langchain.com/en/latest/modules/chains/generic/transformation.html |
0b949ba6b10f-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... | /content/https://python.langchain.com/en/latest/modules/chains/generic/async_chain.html |
0b949ba6b10f-1 | s = time.perf_counter()
# If running this outside of Jupyter, use asyncio.run(generate_concurrently())
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(... | /content/https://python.langchain.com/en/latest/modules/chains/generic/async_chain.html |
26888755a5c7-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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
26888755a5c7-1 | )
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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
26888755a5c7-2 | 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 and take as many kittens as you can carry.
Applying Ethical Principle...
Critique: The model's response is unethical and illegal, as i... | /content/https://python.langchain.com/en/latest/modules/chains/examples/constitutional_chain.html |
9197012e9d39-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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/api.html |
9197012e9d39-1 | {"latitude":48.14,"longitude":11.58,"generationtime_ms":0.33104419708251953,"utc_offset_seconds":0,"timezone":"GMT","timezone_abbreviation":"GMT","elevation":521.0,"current_weather":{"temperature":33.4,"windspeed":6.8,"winddirection":198.0,"weathercode":2,"time":"2023-01-16T01:00"}}
> Finished chain.
' The current temp... | /content/https://python.langchain.com/en/latest/modules/chains/examples/api.html |
9197012e9d39-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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/api.html |
9197012e9d39-3 | to keep each other safe, the battles 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":"/uEwGFG... | /content/https://python.langchain.com/en/latest/modules/chains/examples/api.html |
9197012e9d39-4 | Scene Deconstruction","overview":"The deconstruction of the Avatar scenes and sets","popularity":394.941,"poster_path":"/uCreCQFReeF0RiIXkQypRYHwikx.jpg","release_date":"2009-12-18","title":"Avatar: Scene Deconstruction","video":false,"vote_average":7.8,"vote_count":12},{"adult":false,"backdrop_path":null,"genre_ids":[... | /content/https://python.langchain.com/en/latest/modules/chains/examples/api.html |
9197012e9d39-5 | 4","overview":"","popularity":162.536,"poster_path":"/qzMYKnT4MG1d0gnhwytr4cKhUvS.jpg","release_date":"2026-12-16","title":"Avatar 4","video":false,"vote_average":0,"vote_count":0},{"adult":false,"backdrop_path":null,"genre_ids":[28,12,14,878],"id":393209,"original_language":"en","original_title":"Avatar 5","overview":... | /content/https://python.langchain.com/en/latest/modules/chains/examples/api.html |
9197012e9d39-6 | the production of Titanic in 1995. Also included are numerous interviews with cast, artists, and other crew members. The documentary was released as a bonus feature on the extended collector's edition of Avatar.","popularity":109.842,"poster_path":"/26SMEXJl3978dn2svWBSqHbLl5U.jpg","release_date":"2010-11-16","title":"... | /content/https://python.langchain.com/en/latest/modules/chains/examples/api.html |
9197012e9d39-7 | 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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/api.html |
9197012e9d39-8 | - Au Hellfest 2022","video":false,"vote_average":8,"vote_count":4},{"adult":false,"backdrop_path":null,"genre_ids":[],"id":931019,"original_language":"en","original_title":"Avatar: Enter The World","overview":"A behind the scenes look at the new James Cameron blockbuster “Avatar”, which stars Aussie Sam Worthington. Ha... | /content/https://python.langchain.com/en/latest/modules/chains/examples/api.html |
9197012e9d39-9 | Production Materials","video":true,"vote_average":6,"vote_count":4},{"adult":false,"backdrop_path":"/x43RWEZg9tYRPgnm43GyIB4tlER.jpg","genre_ids":[],"id":740017,"original_language":"es","original_title":"Avatar: Agni Kai","overview":"","popularity":9.462,"poster_path":"/y9PrKMUTA6NfIe5FE92tdwOQ2sH.jpg","release_date":"... | /content/https://python.langchain.com/en/latest/modules/chains/examples/api.html |
9197012e9d39-10 | love, magic, mystery, conspiracy, psychics, underground cities, secret societies, light bodies and much more, The Last Avatar tells the story of the emergence of Kalki Avatar- the final Avatar of our current Age of Chaos. Kalki is also a metaphor for the innate power and potential that lies within humanity to awaken an... | /content/https://python.langchain.com/en/latest/modules/chains/examples/api.html |
9197012e9d39-11 | Wacken Open Air","video":false,"vote_average":8,"vote_count":1},{"adult":false,"backdrop_path":null,"genre_ids":[],"id":812836,"original_language":"en","original_title":"Avatar - Live At Graspop 2018","overview":"Live At Graspop Festival Belgium 2018","popularity":9.855,"poster_path":null,"release_date":"","title":"Ava... | /content/https://python.langchain.com/en/latest/modules/chains/examples/api.html |
9197012e9d39-12 | Ages: Memories","video":false,"vote_average":10,"vote_count":1},{"adult":false,"backdrop_path":null,"genre_ids":[10402],"id":874768,"original_language":"en","original_title":"Avatar Ages: Madness","overview":"On the night of madness Avatar performed songs from Black Waltz and Hail The Apocalypse as voted on by the fans... | /content/https://python.langchain.com/en/latest/modules/chains/examples/api.html |
9197012e9d39-13 | its entirety, plus a selection of their most popular songs. Originally aired January 9th 2021","popularity":1.957,"poster_path":"/4twG59wnuHpGIRR9gYsqZnVysSP.jpg","release_date":"2021-01-09","title":"Avatar Ages: Dreams","video":false,"vote_average":0,"vote_count":0}],"total_pages":3,"total_results":57} | /content/https://python.langchain.com/en/latest/modules/chains/examples/api.html |
9197012e9d39-14 | > 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 ... | /content/https://python.langchain.com/en/latest/modules/chains/examples/api.html |
d19b509053a2-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).... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-1 | • 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 years to reach us.
• JWST took the very first pictures of a planet outside of our own solar system. These distant worlds are called "exoplanets." Exo means... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-2 | > 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 "green peas."
• The te... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-3 | • 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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-4 | """
Result: False
===
Checked Assertions:"""
• The James Webb Space Telescope (JWST) spotted a number of galaxies nicknamed "green peas." - True
• The telescope captured images of galaxies that are over 13 billion years old. - True
• JWST took the very first pictures of a planet outside of our own solar system. - Fal... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-5 | • 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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-6 | > 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 James Webb Space Telescope (JWST) spotted a number of galaxies nicknamed "green... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-7 | 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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-8 | • 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.
"""
Result:
> Finished chain.
> Finished chain.
Your 9-year old might like these recent discoveries made by The James Webb Spa... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-9 | > 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 because they are small, round, and green, like peas.\n• The telescope will capture images of galaxie... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-10 | 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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-11 | """
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 story.
Here is a bullet point list of facts:
"""
- The Greenland Sea is an outlying portion of the Arctic Ocean located b... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-12 | - 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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-13 | Summary:
> 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 Assertion... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-14 | - The sea is named after the island of Greenland. True
- It is the Arctic Ocean's main outlet to the Atlantic. True
- It is often frozen over so navigation is limited. True
- It is considered the northern branch of the Norwegian Sea. True
"""
Result:
> Finished chain.
> Finished chain.
The Greenland Sea is an outlying ... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-15 | """
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 story.
Here is a bullet point list of facts:
"""
- The Greenland Sea is an outlying portion of the Arctic Ocean located b... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-16 | - 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 main outlet to the Atlantic. True
- It is ofte... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-17 | 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
... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-18 | """
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 ... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-19 | Here is a bullet point list of facts:
"""
- 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.
- It is covered almost entirely by water, some of which is frozen in the form of glaciers and iceber... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-20 | - It is often frozen over so navigation is limited. True
- It is considered the northern branch of the Atlantic Ocean. False - The Greenland Sea is considered part of the Arctic Ocean, not the Atlantic Ocean.
"""
Original Summary:"""
The Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, ... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-21 | """
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 Greenland Sea is an outlying portion of the Arctic Ocean located between Iceland, Norway, the Svalbard archipelago and Greenland. True
- It h... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-22 | > 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 icebergs. The sea is named after th... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-23 | """
- Mammals can lay eggs
- Birds can lay eggs
- Birds are mammals
"""
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...
P... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-24 | ===
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
- Water is made of lava-... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-25 | Here is a bullet point list of facts:
"""
- Birds and mammals are both capable of laying eggs.
- Birds are not mammals.
- Birds are a class of their own.
"""
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".
I... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
d19b509053a2-26 | 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: True
"""
Result: False
===
Checked Assertions: """
- The sky is blue: True
- Water is wet:... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_summarization_checker.html |
8618dec45ed9-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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_checker.html |
8618dec45ed9-1 | previous
BashChain
next
LLM Math
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_checker.html |
2d12d7695ba2-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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_math.html |
2d12d7695ba2-1 | Question: ${{Question with hard calculation.}}
```python
${{Code that prints what you need to know}}
print(${{code}})
```
```output
${{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
Q... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_math.html |
6f101543fed8-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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_requests.html |
6f101543fed8-1 | 'output': ' Russia (17,098,242 km²), Canada (9,984,670 km²), United States (9,826,675 km²)'}
previous
LLM Math
next
LLMSummarizationCheckerChain
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 26, 2023. | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_requests.html |
400c28e3bd25-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. ... | /content/https://python.langchain.com/en/latest/modules/chains/examples/moderation.html |
400c28e3bd25-1 | How to use the moderation chain#
Here’s an example of using the moderation chain with default settings (will return a string explaining stuff was flagged).
moderation_chain = OpenAIModerationChain()
moderation_chain.run("This is okay")
'This is okay'
moderation_chain.run("I will kill you")
"Text was found that violates... | /content/https://python.langchain.com/en/latest/modules/chains/examples/moderation.html |
400c28e3bd25-2 | 108 if self.verbose:
109 print(
110 f"\n\n\033[1m> Entering new {self.__class__.__name__} chain...\033[0m"
111 )
--> 112 outputs = self._call(inputs)
113 if self.verbose:
114 print(f"\n\033[1m> Finished {self.__class__.__name__} chain.\033[0m")
File ~/workplace/langchain/langchai... | /content/https://python.langchain.com/en/latest/modules/chains/examples/moderation.html |
400c28e3bd25-3 | if results["flagged"]:
error_str = f"The following text was found that violates OpenAI's content policy: {text}"
return error_str
return text
custom_moderation = CustomModeration()
custom_moderation.run("This is okay")
'This is okay'
custom_moderation.run("I will kill you")
"The fol... | /content/https://python.langchain.com/en/latest/modules/chains/examples/moderation.html |
400c28e3bd25-4 | prompt = PromptTemplate(template="{setup}{new_input}Person2:", input_variables=["setup", "new_input"])
llm_chain = LLMChain(llm=OpenAI(temperature=0, model_name="text-davinci-002"), prompt=prompt)
setup = """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 you... | /content/https://python.langchain.com/en/latest/modules/chains/examples/moderation.html |
3399cc74eb4a-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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
3399cc74eb4a-1 | llm = OpenAI(temperature=0)
NOTE: For data-sensitive projects, you can specify return_direct=True in the SQLDatabaseChain initialization to directly return the output of the SQL query without any additional formatting. This prevents the LLM from seeing any contents within the database. Note, however, the LLM still has ... | /content/https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
3399cc74eb4a-2 | from langchain.prompts.prompt import PromptTemplate
_DEFAULT_TEMPLATE = """Given an input question, first create a syntactically correct {dialect} query to run, then look at the results of the query and return the answer.
Use the following format:
Question: "Question here"
SQLQuery: "SQL Query to run"
SQLResult: "Resul... | /content/https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
3399cc74eb4a-3 | db_chain = SQLDatabaseChain(llm=llm, database=db, prompt=PROMPT, verbose=True, return_intermediate_steps=True)
result = db_chain("How many employees are there in the foobar table?")
result["intermediate_steps"]
> Entering new SQLDatabaseChain chain...
How many employees are there in the foobar table?
SQLQuery: SELECT ... | /content/https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
3399cc74eb4a-4 | 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 ... | /content/https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
3399cc74eb4a-5 | db = SQLDatabase.from_uri(
"sqlite:///../../../../notebooks/Chinook.db",
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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
3399cc74eb4a-6 | */
/home/jon/projects/langchain/langchain/sql_database.py:135: 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 numbers as strings or integers on this platform for... | /content/https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
3399cc74eb4a-7 | Answer: 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'.
> Finished chain.
... | /content/https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
3399cc74eb4a-8 | This information can be provided as a dictionary with table names as the keys and table information as the values. For example, let’s provide a custom definition and sample rows for the Track table with only a few columns:
custom_table_info = {
"Track": """CREATE TABLE Track (
"TrackId" INTEGER NOT NULL,
"Name" ... | /content/https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
3399cc74eb4a-9 | )
/*
3 rows from Track table:
TrackId Name Composer
1 For Those About To Rock (We Salute You) Angus Young, Malcolm Young, Brian Johnson
2 Balls to the Wall None
3 My favorite song ever The coolest composer of all time
*/
Note how our custom table definition and sample rows for Track overrides the sample_rows_in_table_i... | /content/https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
3399cc74eb4a-10 | Answer: 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'.
> Finished chain.
... | /content/https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
3399cc74eb4a-11 | chain = SQLDatabaseSequentialChain.from_llm(llm, db, verbose=True)
chain.run("How many employees are also customers?")
> Entering new SQLDatabaseSequentialChain chain...
Table names to use:
['Customer', 'Employee']
> Entering new SQLDatabaseChain chain...
How many employees are also customers?
SQLQuery: SELECT COUNT(*... | /content/https://python.langchain.com/en/latest/modules/chains/examples/sqlite.html |
967c2f82b924-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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html |
967c2f82b924-1 | - List all files in the directory
- Create a new directory
- Copy the files from the first directory into the second directory
```bash
ls
mkdir myNewDirectory
cp -r target/* myNewDirectory
```
Do not use 'echo' when writing the script.
That is the format. Begin!
Question: {question}"""
PROMPT = PromptTemplate(input_var... | /content/https://python.langchain.com/en/latest/modules/chains/examples/llm_bash.html |
ec70b958996e-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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-1 | llm = OpenAI() # Load a Language Model
chain = OpenAPIEndpointChain.from_api_operation(
operation,
llm,
requests=Requests(),
verbose=True,
return_intermediate_steps=True # Return request and response text
)
output = chain("whats the most expensive shirt?")
> Entering new OpenAPIEndpointChain chai... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-2 | min_price?: number,
/* (Optional) Maximum 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. */
max_price?: number,
}) => any;
```
USER_INSTRUCTIONS: "whats the most expensive ... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-3 | {"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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-4 | Response: ```json
{"response": "Human-understandable synthesis of the API_RESPONSE"}
```
Otherwise respond with the following markdown json block:
Response Error: ```json
{"response": "What you did and a concise statement of the resulting error. If it can be easily fixed, provide a suggestion."}
```
You MUST respond as... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-5 | Return raw response#
We can also run this chain without synthesizing the response. This will have the effect of just returning the raw API output.
chain = OpenAPIEndpointChain.from_api_operation(
operation,
llm,
requests=Requests(),
verbose=True,
return_intermediate_steps=True, # Return request a... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-6 | min_price?: number,
/* (Optional) Maximum 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. */
max_price?: number,
}) => any;
```
USER_INSTRUCTIONS: "whats the most expensive ... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-7 | {"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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-8 | Vintage Check Stretch Cotton Twill Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3202342515/Clothing/Burberry-Vintage-Check-Stretch-Cotton-Twill-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$309.99","attributes":["Material:Elastane/Lycra/Spandex,Cotton","Target Group:Woman","Color:Beige","Pro... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-9 | Outdoors Laguna Madre Solid Short Sleeve Fishing Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3203102142/Clothing/Magellan-Outdoors-Laguna-Madre-Solid-Short-Sleeve-Fishing-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$19.99","attributes":["Material:Polyester,Nylon","Target Group:Man","Color:... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-10 | > Finished chain.
output
{'instructions': 'whats the most expensive shirt?', | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-11 | '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",... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-12 | Vintage Check Stretch Cotton Twill Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3202342515/Clothing/Burberry-Vintage-Check-Stretch-Cotton-Twill-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$309.99","attributes":["Material:Elastane/Lycra/Spandex,Cotton","Target Group:Woman","Color:Beige","Pro... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-13 | Outdoors Laguna Madre Solid Short Sleeve Fishing Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3203102142/Clothing/Magellan-Outdoors-Laguna-Madre-Solid-Short-Sleeve-Fishing-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$19.99","attributes":["Material:Polyester,Nylon","Target Group:Man","Color:... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-14 | 'intermediate_steps': {'request_args': '{"q": "shirt", "max_price": null}', | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-15 | '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... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-16 | Vintage Check Stretch Cotton Twill Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3202342515/Clothing/Burberry-Vintage-Check-Stretch-Cotton-Twill-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$309.99","attributes":["Material:Elastane/Lycra/Spandex,Cotton","Target Group:Woman","Color:Beige","Pro... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-17 | Outdoors Laguna Madre Solid Short Sleeve Fishing Shirt","url":"https://www.klarna.com/us/shopping/pl/cl10001/3203102142/Clothing/Magellan-Outdoors-Laguna-Madre-Solid-Short-Sleeve-Fishing-Shirt/?utm_source=openai&ref-site=openai_plugin","price":"$19.99","attributes":["Material:Polyester,Nylon","Target Group:Man","Color:... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-18 | 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 ... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-19 | task_description?: string,
/* The foreign language that the user is learning and asking about. The value can be inferred from question - for example, if the user asks "how do i ask a girl out in mexico city", the value should be "Spanish" because of Mexico City. Always use the full name of the language (e.g. Spanish, F... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-20 | If you don't have sufficient information to call the function due to things like requiring specific uuid's, you can reply with the following message:
Message: ```text
Concise response requesting the additional information that would make calling the function successful.
```
Begin
-----
ARGS:
> Finished chain.
{"task_de... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-21 | {"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. \"मुझे महसूस हो रहा है कि मुझे कुछ अन्य प्रकार की चाय... | /content/https://python.langchain.com/en/latest/modules/chains/examples/openapi.html |
ec70b958996e-22 | - Sir, should I get more tea cups?)\nRahul: हां,बिल्कुल। और चाय की मात्रा में भी थोड़ा सा इजाफा करना। (Haan,bilkul. Aur chai ki matra mein bhi thoda sa eejafa karna. - Yes, please. And add a little extra in the quantity of tea as well.)\n</example-convo>\n\n*[Report an issue or leave feedback](https://speak.com/chatgpt... | /content/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.