id stringlengths 14 16 | text stringlengths 31 2.73k | source stringlengths 56 166 |
|---|---|---|
e95c52c66e48-22 | '{"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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/openapi.html |
e95c52c66e48-23 | language=\\"Hindi\\">\\n<context>At home during breakfast.</context>\\nPreeti: सर, क्या main aur cups chai lekar aaun? (Sir,kya main aur cups chai lekar aaun? - Sir, should I get more tea cups?)\\nRahul: हां,बिल्कुल। और चाय की मात्रा में भी थोड़ा सा इजाफा करना। (Haan,bilkul. Aur chai ki matra mein bhi thoda sa eejafa k... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/openapi.html |
e95c52c66e48-24 | previous
Moderation
next
PAL
Contents
Load the spec
Select the Operation
Construct the chain
Return raw response
Example POST message
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/openapi.html |
f1c33953a4bf-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(model_name='code-davinci-002', temperature=0, max_tokens=512)
Math Prompt#
... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/pal.html |
f1c33953a4bf-1 | objects = []
objects += [('booklet', 'blue')] * 2
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 obj... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/pal.html |
f1c33953a4bf-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/pal.html |
8ad7c9914a2a-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_math.html |
8ad7c9914a2a-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_math.html |
b41adbe44391-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/moderation.html |
b41adbe44391-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/moderation.html |
b41adbe44391-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/moderation.html |
b41adbe44391-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/moderation.html |
b41adbe44391-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/moderation.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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 than ever before.
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 ... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-12 | 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: """
- The sky is red: False
- Water is made of lava: False
- The sun is a star: Tr... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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 glaciers... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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 locat... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-19 | > 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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b5faf5300d1b-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_summarization_checker.html |
b737a5d8ceab-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/constitutional_chain.html |
b737a5d8ceab-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/constitutional_chain.html |
b737a5d8ceab-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/constitutional_chain.html |
6750853d5c3e-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_bash.html |
6750853d5c3e-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_bash.html |
f2c61e680ced-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
f2c61e680ced-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
f2c61e680ced-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
f2c61e680ced-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
f2c61e680ced-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
f2c61e680ced-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
f2c61e680ced-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
f2c61e680ced-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
f2c61e680ced-8 | 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 Sebastian Bach'), ('Suite for Solo Cello No. 1 in G Major, BWV 1007: I. Prélude'... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
f2c61e680ced-9 | 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.chains import SQLDatabaseSe... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/sqlite.html |
9143ca8b8abb-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://langchain-cn.readthedocs.io/en/latest/modules/chains/examples/llm_checker.html |
96645f1d7582-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/sequential_chains.html |
96645f1d7582-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/sequential_chains.html |
96645f1d7582-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/sequential_chains.html |
96645f1d7582-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/sequential_chains.html |
96645f1d7582-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/sequential_chains.html |
96645f1d7582-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/sequential_chains.html |
96645f1d7582-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/sequential_chains.html |
96645f1d7582-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/sequential_chains.html |
96645f1d7582-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/sequential_chains.html |
2b24fced623e-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/transformation.html |
7b34a0cdb8ec-0 | .ipynb
.pdf
LLM Chain
Contents
Single Input
Multiple Inputs
From string
LLM Chain#
This notebook showcases a simple LLM chain.
from langchain import PromptTemplate, OpenAI, LLMChain
Single Input#
First, lets go over an example using a single input
template = """Question: {question}
Answer: Let's think step by step.""... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/llm_chain.html |
7b34a0cdb8ec-1 | Write a sad poem about ducks.
> Finished LLMChain chain.
"\n\nThe ducks swim in the pond,\nTheir feathers so soft and warm,\nBut they can't help but feel so forlorn.\n\nTheir quacks echo in the air,\nBut no one is there to hear,\nFor they have no one to share.\n\nThe ducks paddle around in circles,\nTheir heads hung lo... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/llm_chain.html |
7b34a0cdb8ec-2 | next
Sequential Chains
Contents
Single Input
Multiple Inputs
From string
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/llm_chain.html |
edd9fb3d2cd1-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/serialization.html |
edd9fb3d2cd1-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/serialization.html |
edd9fb3d2cd1-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/serialization.html |
8bd751a5a454-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/async_chain.html |
8bd751a5a454-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/async_chain.html |
2c9c7cf53cc0-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://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/from_hub.html |
2c9c7cf53cc0-1 | 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 from the Fraternal Order of Police to former judges appointed by ... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/generic/from_hub.html |
bb2d798747f6-0 | .ipynb
.pdf
Analyze Document
Contents
Summarize
Question Answering
Analyze Document#
The AnalyzeDocumentChain is more of an end to chain. This chain takes in a single document, splits it up, and then runs it through a CombineDocumentsChain. This can be used as more of an end-to-end chain.
with open("../../state_of_th... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/analyze_document.html |
bb2d798747f6-1 | qa_chain = load_qa_chain(llm, chain_type="map_reduce")
qa_document_chain = AnalyzeDocumentChain(combine_docs_chain=qa_chain)
qa_document_chain.run(input_document=state_of_the_union, question="what did the president say about justice breyer?")
' The president thanked Justice Breyer for his service.'
previous
Transformat... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/analyze_document.html |
78cf778b8086-0 | .ipynb
.pdf
Vector DB Text Generation
Contents
Prepare Data
Set Up Vector DB
Set Up LLM Chain with Custom Prompt
Generate Text
Vector DB Text Generation#
This notebook walks through how to use LangChain for text generation over a vector index. This is useful if we want to generate text that is able to draw from a lar... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
78cf778b8086-1 | relative_path = markdown_file.relative_to(repo_path)
github_url = f"https://github.com/{repo_owner}/{repo_name}/blob/{git_sha}/{relative_path}"
yield Document(page_content=f.read(), metadata={"source": github_url})
sources = get_github_docs("yirenlu92", "deno-manual-forked")
source_chunk... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
78cf778b8086-2 | Generate Text#
Finally, we write a function to apply our inputs to the chain. The function takes an input parameter topic. We find the documents in the vector index that correspond to that topic, and use them as additional context in our simple LLM chain.
def generate_blog_post(topic):
docs = search_index.similarit... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
78cf778b8086-3 | [{'text': '\n\nEnvironment variables are a great way to store and access sensitive information in your Deno applications. Deno offers built-in support for environment variables with `Deno.env`, and you can also use a `.env` file to store and access environment variables.\n\nUsing `Deno.env` is simple. It has getter and... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
78cf778b8086-4 | will set the environment variable `VAR` to `hello` before running the command. We can then access this variable in our code using the `Deno.env.get()` function. For example, if we ran the following command:\n\n```\nVAR=hello && deno eval "console.log(\'Deno: \' + Deno.env.get(\'VAR'}, {'text': '\n\nEnvironment variable... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
78cf778b8086-5 | added in Deno version 1.6.0, and it is now available for use in Deno applications.\n\nEnvironment variables are used to store information that can be used by programs. They are typically used to store configuration information, such as the location of a database or the name of a user. In Deno, environment variables are... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
78cf778b8086-6 | previous
Retrieval Question Answering with Sources
next
API Chains
Contents
Prepare Data
Set Up Vector DB
Set Up LLM Chain with Custom Prompt
Generate Text
By Harrison Chase
© Copyright 2023, Harrison Chase.
Last updated on Apr 18, 2023. | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/vector_db_text_generation.html |
4ae248b48758-0 | .ipynb
.pdf
Retrieval Question/Answering
Contents
Chain Type
Custom Prompts
Return Source Documents
Retrieval Question/Answering#
This example showcases question answering over an index.
from langchain.embeddings.openai import OpenAIEmbeddings
from langchain.vectorstores import Chroma
from langchain.text_splitter imp... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/vector_db_qa.html |
4ae248b48758-1 | There are two ways to load different chain types. First, you can specify the chain type argument in the from_chain_type method. This allows you to pass in the name of the chain type you want to use. For example, in the below we change the chain type to map_reduce.
qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_ty... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/vector_db_qa.html |
4ae248b48758-2 | qa.run(query)
" The president said that Ketanji Brown Jackson is one of the nation's top legal minds, a former top litigator in private practice, a former federal public defender, and from a family of public school educators and police officers. He also said that she is a consensus builder and has received a broad rang... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/vector_db_qa.html |
4ae248b48758-3 | qa = RetrievalQA.from_chain_type(llm=OpenAI(), chain_type="stuff", retriever=docsearch.as_retriever(), return_source_documents=True)
query = "What did the president say about Ketanji Brown Jackson"
result = qa({"query": query})
result["result"]
" The president said that Ketanji Brown Jackson is one of the nation's top ... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/vector_db_qa.html |
4ae248b48758-4 | Document(page_content='A former top litigator in private practice. A former federal public defender. And from a family of public school educators and police officers. A consensus builder. Since she’s been nominated, she’s received a broad range of support—from the Fraternal Order of Police to former judges appointed by... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/vector_db_qa.html |
4ae248b48758-5 | Document(page_content='And for our LGBTQ+ Americans, let’s finally get the bipartisan Equality Act to my desk. The onslaught of state laws targeting transgender Americans and their families is wrong. \n\nAs I said last year, especially to our younger transgender Americans, I will always have your back as your President... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/vector_db_qa.html |
4ae248b48758-6 | Document(page_content='Tonight, I’m announcing a crackdown on these companies overcharging American businesses and consumers. \n\nAnd as Wall Street firms take over more nursing homes, quality in those homes has gone down and costs have gone up. \n\nThat ends on my watch. \n\nMedicare is going to set higher standards ... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/vector_db_qa.html |
302ea95dbf72-0 | .ipynb
.pdf
Question Answering with Sources
Contents
Prepare Data
Quickstart
The stuff Chain
The map_reduce Chain
The refine Chain
The map-rerank Chain
Question Answering with Sources#
This notebook walks through how to use LangChain for question answering with sources over a list of documents. It covers four differe... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/qa_with_sources.html |
302ea95dbf72-1 | from langchain.chains.qa_with_sources import load_qa_with_sources_chain
from langchain.llms import OpenAI
Quickstart#
If you just want to get started as quickly as possible, this is the recommended way to do it:
chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type="stuff")
query = "What did the presiden... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/qa_with_sources.html |
302ea95dbf72-2 | PROMPT = PromptTemplate(template=template, input_variables=["summaries", "question"])
chain = load_qa_with_sources_chain(OpenAI(temperature=0), chain_type="stuff", prompt=PROMPT)
query = "What did the president say about Justice Breyer"
chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'out... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/qa_with_sources.html |
302ea95dbf72-3 | ' None',
' None',
' None'],
'output_text': ' The president thanked Justice Breyer for his service.\nSOURCES: 30-pl'}
Custom Prompts
You can also use your own prompts with this chain. In this example, we will respond in Italian.
question_prompt_template = """Use the following portion of a long document to see if an... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/qa_with_sources.html |
302ea95dbf72-4 | chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'intermediate_steps': ["\nStasera vorrei onorare qualcuno che ha dedicato la sua vita a servire questo paese: il giustizia Stephen Breyer - un veterano dell'esercito, uno studioso costituzionale e un giustizia in uscita della Corte Suprema d... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/qa_with_sources.html |
302ea95dbf72-5 | chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'output_text': "\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked him for his service and praised his c... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/qa_with_sources.html |
302ea95dbf72-6 | chain({"input_documents": docs, "question": query}, return_only_outputs=True)
{'intermediate_steps': ['\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service.... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/qa_with_sources.html |
302ea95dbf72-7 | '\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal public defender, and... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/qa_with_sources.html |
302ea95dbf72-8 | '\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal public defender, and... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/qa_with_sources.html |
302ea95dbf72-9 | 'output_text': '\n\nThe president said that he was honoring Justice Breyer for his dedication to serving the country and that he was a retiring Justice of the United States Supreme Court. He also thanked Justice Breyer for his service, noting his background as a top litigator in private practice, a former federal publi... | https://langchain-cn.readthedocs.io/en/latest/modules/chains/index_examples/qa_with_sources.html |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.